repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
danielsomerfield/go-strong-auth-plugin | src/main/java/com/thoughtworks/go/strongauth/authentication/Authenticator.java | // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java
// public class Constants {
// public static final String PLUGIN_ID = "strongauth";
// }
//
// Path: src/main/java/com/thoughtworks/util/Functional.java
// public static <T, U> Optional<U> flatMap(Optional<? extends T> maybeValue, final Function<T, Optional<U>> transformation) {
// return maybeValue.isPresent() ? transformation.apply(maybeValue.get()) : Optional.<U>absent();
// }
| import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.strongauth.util.Constants;
import org.apache.commons.codec.DecoderException;
import java.util.List;
import static com.thoughtworks.util.Functional.flatMap;
import static java.lang.String.format; | package com.thoughtworks.go.strongauth.authentication;
public class Authenticator {
public final String pluginId = Constants.PLUGIN_ID;
private static final Logger LOGGER = Logger.getLoggerFor(Authenticator.class);
private final List<? extends HashProvider> hashProviders;
public Authenticator(
final PrincipalDetailSource principalDetailSource,
final List<? extends HashProvider> hashProviders
) {
this.principalDetailSource = principalDetailSource;
this.hashProviders = hashProviders;
}
private PrincipalDetailSource principalDetailSource;
public Optional<Principal> authenticate(final String username, final String password) {
LOGGER.info(format("Login attempt for user %s", username)); | // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java
// public class Constants {
// public static final String PLUGIN_ID = "strongauth";
// }
//
// Path: src/main/java/com/thoughtworks/util/Functional.java
// public static <T, U> Optional<U> flatMap(Optional<? extends T> maybeValue, final Function<T, Optional<U>> transformation) {
// return maybeValue.isPresent() ? transformation.apply(maybeValue.get()) : Optional.<U>absent();
// }
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/Authenticator.java
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.strongauth.util.Constants;
import org.apache.commons.codec.DecoderException;
import java.util.List;
import static com.thoughtworks.util.Functional.flatMap;
import static java.lang.String.format;
package com.thoughtworks.go.strongauth.authentication;
public class Authenticator {
public final String pluginId = Constants.PLUGIN_ID;
private static final Logger LOGGER = Logger.getLoggerFor(Authenticator.class);
private final List<? extends HashProvider> hashProviders;
public Authenticator(
final PrincipalDetailSource principalDetailSource,
final List<? extends HashProvider> hashProviders
) {
this.principalDetailSource = principalDetailSource;
this.hashProviders = hashProviders;
}
private PrincipalDetailSource principalDetailSource;
public Optional<Principal> authenticate(final String username, final String password) {
LOGGER.info(format("Login attempt for user %s", username)); | Optional<Principal> maybePrincipal = flatMap(principalDetailSource.byUsername(username), new Function<PrincipalDetail, Optional<Principal>>() { |
danielsomerfield/go-strong-auth-plugin | src/main/java/com/thoughtworks/go/strongauth/authentication/hash/BCryptProvider.java | // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/HashProvider.java
// public interface HashProvider {
// boolean validateHash(final String password, final PrincipalDetail principalDetail);
//
// boolean canHandle(String hashConfig);
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java
// @Value
// public class PrincipalDetail {
// private final String username;
// private final String passwordHash;
// private final String salt;
// private final String hashConfiguration;
// }
| import com.thoughtworks.go.strongauth.authentication.HashProvider;
import com.thoughtworks.go.strongauth.authentication.PrincipalDetail;
import org.springframework.security.crypto.bcrypt.BCrypt; | package com.thoughtworks.go.strongauth.authentication.hash;
public class BCryptProvider implements HashProvider {
@Override | // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/HashProvider.java
// public interface HashProvider {
// boolean validateHash(final String password, final PrincipalDetail principalDetail);
//
// boolean canHandle(String hashConfig);
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java
// @Value
// public class PrincipalDetail {
// private final String username;
// private final String passwordHash;
// private final String salt;
// private final String hashConfiguration;
// }
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/BCryptProvider.java
import com.thoughtworks.go.strongauth.authentication.HashProvider;
import com.thoughtworks.go.strongauth.authentication.PrincipalDetail;
import org.springframework.security.crypto.bcrypt.BCrypt;
package com.thoughtworks.go.strongauth.authentication.hash;
public class BCryptProvider implements HashProvider {
@Override | public boolean validateHash(String password, PrincipalDetail principalDetail) { |
danielsomerfield/go-strong-auth-plugin | src/test/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoderTest.java | // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/AuthenticationRequest.java
// @Value
// public class AuthenticationRequest {
// private final String username;
// private final String password;
// }
| import com.google.common.base.Optional;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package com.thoughtworks.go.strongauth.wire;
public class GoAuthenticationRequestDecoderTest {
@Test
public void testDecodeAuthenticationValidRequest() {
GoPluginApiRequest request = mock(GoPluginApiRequest.class);
when(request.requestBody()).thenReturn("{\"username\":\"uname\",\"password\":\"pword\"}");
GoAuthenticationRequestDecoder decoder = new GoAuthenticationRequestDecoder(); | // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/AuthenticationRequest.java
// @Value
// public class AuthenticationRequest {
// private final String username;
// private final String password;
// }
// Path: src/test/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoderTest.java
import com.google.common.base.Optional;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package com.thoughtworks.go.strongauth.wire;
public class GoAuthenticationRequestDecoderTest {
@Test
public void testDecodeAuthenticationValidRequest() {
GoPluginApiRequest request = mock(GoPluginApiRequest.class);
when(request.requestBody()).thenReturn("{\"username\":\"uname\",\"password\":\"pword\"}");
GoAuthenticationRequestDecoder decoder = new GoAuthenticationRequestDecoder(); | Optional<AuthenticationRequest> maybeRequest = decoder.decode(request); |
danielsomerfield/go-strong-auth-plugin | src/main/java/com/thoughtworks/go/strongauth/config/GoAPI.java | // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java
// public class Constants {
// public static final String PLUGIN_ID = "strongauth";
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java
// public class Json {
// private static Gson gson = new Gson();
//
// public static Map<String, String> toMapOfStrings(String jsonValue) {
// Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType();
// return gson.fromJson(jsonValue, mapOfStringToStringType);
// }
//
// public static Map toMap(String jsonValue) {
// return gson.fromJson(jsonValue, Map.class);
// }
//
// public static String toJson(Object anything) {
// return gson.toJson(anything);
// }
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java
// public class PluginConfigurationDecoder {
// public PluginConfiguration decode(GoApiResponse response) {
// if (response.responseCode() == 200) {
// return parseConfiguration(response.responseBody());
// } else {
// return defaultConfiguration();
// }
// }
//
// private PluginConfiguration parseConfiguration(String body) {
// if (body == null) {
// return defaultConfiguration();
// } else {
// return fromMap(Json.toMapOfStrings(body));
// }
// }
//
// private PluginConfiguration fromMap(Map<String, String> configMap) {
// return new PluginConfiguration(configMap.get("PASSWORD_FILE_PATH"));
// }
//
// public PluginConfiguration defaultConfiguration() {
// return new PluginConfiguration();
// }
// }
| import com.google.common.collect.ImmutableMap;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.DefaultGoApiRequest;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.strongauth.util.Constants;
import com.thoughtworks.go.strongauth.util.Json;
import com.thoughtworks.go.strongauth.wire.PluginConfigurationDecoder; | package com.thoughtworks.go.strongauth.config;
public class GoAPI {
public final String pluginId = Constants.PLUGIN_ID;
private static final Logger LOGGER = Logger.getLoggerFor(GoAPI.class);
private final GoPluginIdentifier goPluginIdentifier;
private final GoApplicationAccessor goApplicationAccessor; | // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java
// public class Constants {
// public static final String PLUGIN_ID = "strongauth";
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java
// public class Json {
// private static Gson gson = new Gson();
//
// public static Map<String, String> toMapOfStrings(String jsonValue) {
// Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType();
// return gson.fromJson(jsonValue, mapOfStringToStringType);
// }
//
// public static Map toMap(String jsonValue) {
// return gson.fromJson(jsonValue, Map.class);
// }
//
// public static String toJson(Object anything) {
// return gson.toJson(anything);
// }
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java
// public class PluginConfigurationDecoder {
// public PluginConfiguration decode(GoApiResponse response) {
// if (response.responseCode() == 200) {
// return parseConfiguration(response.responseBody());
// } else {
// return defaultConfiguration();
// }
// }
//
// private PluginConfiguration parseConfiguration(String body) {
// if (body == null) {
// return defaultConfiguration();
// } else {
// return fromMap(Json.toMapOfStrings(body));
// }
// }
//
// private PluginConfiguration fromMap(Map<String, String> configMap) {
// return new PluginConfiguration(configMap.get("PASSWORD_FILE_PATH"));
// }
//
// public PluginConfiguration defaultConfiguration() {
// return new PluginConfiguration();
// }
// }
// Path: src/main/java/com/thoughtworks/go/strongauth/config/GoAPI.java
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.DefaultGoApiRequest;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.strongauth.util.Constants;
import com.thoughtworks.go.strongauth.util.Json;
import com.thoughtworks.go.strongauth.wire.PluginConfigurationDecoder;
package com.thoughtworks.go.strongauth.config;
public class GoAPI {
public final String pluginId = Constants.PLUGIN_ID;
private static final Logger LOGGER = Logger.getLoggerFor(GoAPI.class);
private final GoPluginIdentifier goPluginIdentifier;
private final GoApplicationAccessor goApplicationAccessor; | private final PluginConfigurationDecoder pluginConfigurationDecoder; |
danielsomerfield/go-strong-auth-plugin | src/main/java/com/thoughtworks/go/strongauth/config/GoAPI.java | // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java
// public class Constants {
// public static final String PLUGIN_ID = "strongauth";
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java
// public class Json {
// private static Gson gson = new Gson();
//
// public static Map<String, String> toMapOfStrings(String jsonValue) {
// Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType();
// return gson.fromJson(jsonValue, mapOfStringToStringType);
// }
//
// public static Map toMap(String jsonValue) {
// return gson.fromJson(jsonValue, Map.class);
// }
//
// public static String toJson(Object anything) {
// return gson.toJson(anything);
// }
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java
// public class PluginConfigurationDecoder {
// public PluginConfiguration decode(GoApiResponse response) {
// if (response.responseCode() == 200) {
// return parseConfiguration(response.responseBody());
// } else {
// return defaultConfiguration();
// }
// }
//
// private PluginConfiguration parseConfiguration(String body) {
// if (body == null) {
// return defaultConfiguration();
// } else {
// return fromMap(Json.toMapOfStrings(body));
// }
// }
//
// private PluginConfiguration fromMap(Map<String, String> configMap) {
// return new PluginConfiguration(configMap.get("PASSWORD_FILE_PATH"));
// }
//
// public PluginConfiguration defaultConfiguration() {
// return new PluginConfiguration();
// }
// }
| import com.google.common.collect.ImmutableMap;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.DefaultGoApiRequest;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.strongauth.util.Constants;
import com.thoughtworks.go.strongauth.util.Json;
import com.thoughtworks.go.strongauth.wire.PluginConfigurationDecoder; | package com.thoughtworks.go.strongauth.config;
public class GoAPI {
public final String pluginId = Constants.PLUGIN_ID;
private static final Logger LOGGER = Logger.getLoggerFor(GoAPI.class);
private final GoPluginIdentifier goPluginIdentifier;
private final GoApplicationAccessor goApplicationAccessor;
private final PluginConfigurationDecoder pluginConfigurationDecoder;
public GoAPI(
GoPluginIdentifier goPluginIdentifier,
GoApplicationAccessor goApplicationAccessor,
PluginConfigurationDecoder pluginConfigurationDecoder
) {
this.goPluginIdentifier = goPluginIdentifier;
this.goApplicationAccessor = goApplicationAccessor;
this.pluginConfigurationDecoder = pluginConfigurationDecoder;
}
public PluginConfiguration getPluginConfiguration() {
DefaultGoApiRequest request = new DefaultGoApiRequest("go.processor.plugin-settings.get", "1.0", goPluginIdentifier); | // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java
// public class Constants {
// public static final String PLUGIN_ID = "strongauth";
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java
// public class Json {
// private static Gson gson = new Gson();
//
// public static Map<String, String> toMapOfStrings(String jsonValue) {
// Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType();
// return gson.fromJson(jsonValue, mapOfStringToStringType);
// }
//
// public static Map toMap(String jsonValue) {
// return gson.fromJson(jsonValue, Map.class);
// }
//
// public static String toJson(Object anything) {
// return gson.toJson(anything);
// }
// }
//
// Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java
// public class PluginConfigurationDecoder {
// public PluginConfiguration decode(GoApiResponse response) {
// if (response.responseCode() == 200) {
// return parseConfiguration(response.responseBody());
// } else {
// return defaultConfiguration();
// }
// }
//
// private PluginConfiguration parseConfiguration(String body) {
// if (body == null) {
// return defaultConfiguration();
// } else {
// return fromMap(Json.toMapOfStrings(body));
// }
// }
//
// private PluginConfiguration fromMap(Map<String, String> configMap) {
// return new PluginConfiguration(configMap.get("PASSWORD_FILE_PATH"));
// }
//
// public PluginConfiguration defaultConfiguration() {
// return new PluginConfiguration();
// }
// }
// Path: src/main/java/com/thoughtworks/go/strongauth/config/GoAPI.java
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.DefaultGoApiRequest;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.strongauth.util.Constants;
import com.thoughtworks.go.strongauth.util.Json;
import com.thoughtworks.go.strongauth.wire.PluginConfigurationDecoder;
package com.thoughtworks.go.strongauth.config;
public class GoAPI {
public final String pluginId = Constants.PLUGIN_ID;
private static final Logger LOGGER = Logger.getLoggerFor(GoAPI.class);
private final GoPluginIdentifier goPluginIdentifier;
private final GoApplicationAccessor goApplicationAccessor;
private final PluginConfigurationDecoder pluginConfigurationDecoder;
public GoAPI(
GoPluginIdentifier goPluginIdentifier,
GoApplicationAccessor goApplicationAccessor,
PluginConfigurationDecoder pluginConfigurationDecoder
) {
this.goPluginIdentifier = goPluginIdentifier;
this.goApplicationAccessor = goApplicationAccessor;
this.pluginConfigurationDecoder = pluginConfigurationDecoder;
}
public PluginConfiguration getPluginConfiguration() {
DefaultGoApiRequest request = new DefaultGoApiRequest("go.processor.plugin-settings.get", "1.0", goPluginIdentifier); | request.setRequestBody(Json.toJson(ImmutableMap.of("plugin-id", Constants.PLUGIN_ID))); |
wso2/maven-tools | wso2-maven-json-merge-plugin/src/test/java/UtilsTest.java | // Path: wso2-maven-json-merge-plugin/src/main/java/org/wso2/maven/Utils.java
// public class Utils {
//
// public static Map getReadMap(String path) throws MojoExecutionException {
//
// if (Paths.get(path).toFile().exists()) {
// Gson gson = new Gson();
// try (FileInputStream fileInputStream = new FileInputStream(path)) {
// Reader input = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
// return gson.fromJson(input, Map.class);
// } catch (IOException e) {
// throw new MojoExecutionException("Error while reading json file", e);
// }
// } else {
// return new HashMap();
// }
// }
//
// public static String convertIntoJson(Map input) {
//
// Gson gson = new GsonBuilder().setPrettyPrinting().setLenient().create();
// return gson.toJson(input);
// }
//
// public static Map<String, Object> mergeMaps(Map<String, Object> baseMap, Map<String, Object> input, boolean isChildMergeEnabled) {
// for (Map.Entry<String, Object> entry : input.entrySet()) {
// String key = entry.getKey();
// Object value = entry.getValue();
// Object returnedValue = baseMap.get(key);
// if (returnedValue == null) {
// baseMap.put(key, value);
// } else if (returnedValue instanceof Map && isChildMergeEnabled) {
// value = mergeMaps((Map<String, Object>) returnedValue, (Map<String, Object>) value, true);
// baseMap.put(key, value);
// }
// }
// return baseMap;
// }
//
// }
| import com.google.gson.Gson;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.maven.Utils;
import java.util.List;
import java.util.Map; | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class UtilsTest {
@Test(dataProvider = "input")
public void testMerge(String input, String output, String expected) {
Map inputMap = new Gson().fromJson(input, Map.class);
Map outputMap = new Gson().fromJson(output, Map.class);
Map expectedMap = new Gson().fromJson(expected, Map.class); | // Path: wso2-maven-json-merge-plugin/src/main/java/org/wso2/maven/Utils.java
// public class Utils {
//
// public static Map getReadMap(String path) throws MojoExecutionException {
//
// if (Paths.get(path).toFile().exists()) {
// Gson gson = new Gson();
// try (FileInputStream fileInputStream = new FileInputStream(path)) {
// Reader input = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
// return gson.fromJson(input, Map.class);
// } catch (IOException e) {
// throw new MojoExecutionException("Error while reading json file", e);
// }
// } else {
// return new HashMap();
// }
// }
//
// public static String convertIntoJson(Map input) {
//
// Gson gson = new GsonBuilder().setPrettyPrinting().setLenient().create();
// return gson.toJson(input);
// }
//
// public static Map<String, Object> mergeMaps(Map<String, Object> baseMap, Map<String, Object> input, boolean isChildMergeEnabled) {
// for (Map.Entry<String, Object> entry : input.entrySet()) {
// String key = entry.getKey();
// Object value = entry.getValue();
// Object returnedValue = baseMap.get(key);
// if (returnedValue == null) {
// baseMap.put(key, value);
// } else if (returnedValue instanceof Map && isChildMergeEnabled) {
// value = mergeMaps((Map<String, Object>) returnedValue, (Map<String, Object>) value, true);
// baseMap.put(key, value);
// }
// }
// return baseMap;
// }
//
// }
// Path: wso2-maven-json-merge-plugin/src/test/java/UtilsTest.java
import com.google.gson.Gson;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.maven.Utils;
import java.util.List;
import java.util.Map;
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class UtilsTest {
@Test(dataProvider = "input")
public void testMerge(String input, String output, String expected) {
Map inputMap = new Gson().fromJson(input, Map.class);
Map outputMap = new Gson().fromJson(output, Map.class);
Map expectedMap = new Gson().fromJson(expected, Map.class); | Utils.mergeMaps(inputMap, outputMap, false); |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import feign.Headers;
import feign.Param;
import feign.RequestLine;
import feign.Response;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
import java.io.File; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact;
public interface CAppMgtServiceStub {
@RequestLine("GET /management/login")
@Headers("accept: application/json; charset=utf-8") | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import feign.Response;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
import java.io.File;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact;
public interface CAppMgtServiceStub {
@RequestLine("GET /management/login")
@Headers("accept: application/json; charset=utf-8") | Response doAuthenticate() throws CAppMgtServiceStubException; |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/HTTPSClientUtil.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import java.io.File;
import feign.Response;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class HTTPSClientUtil {
/**
* Avoids Instantiation.
*/
private HTTPSClientUtil() {
}
public static Response doAuthenticate(String serverUrl, String username, String password) throws | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/HTTPSClientUtil.java
import java.io.File;
import feign.Response;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class HTTPSClientUtil {
/**
* Avoids Instantiation.
*/
private HTTPSClientUtil() {
}
public static Response doAuthenticate(String serverUrl, String username, String password) throws | CAppMgtServiceStubException{ |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/EICAppHandler.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public class Constants {
//
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
// public static final int CLIENT_READ_TIMEOUT = 5000;
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
// public static final String MI_SERVER = "mi";
// public static final String EI_SERVER = "ei";
//
// public static final String AUTHORIZATION_HEADER = "Authorization";
// public static final String BASIC = "Basic ";
// public static final String ACCESS_TOKEN = "AccessToken";
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.activation.DataHandler;
import org.apache.axiom.util.base64.Base64Utils;
import org.apache.commons.httpclient.Header;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.wso2.carbon.application.mgt.stub.upload.types.carbon.UploadedFileItem;
import org.wso2.carbon.stub.ApplicationAdminStub;
import org.wso2.carbon.stub.CarbonAppUploaderStub;
import org.wso2.maven.car.artifact.util.Constants;
import java.io.File; | }
}
private CarbonAppUploaderStub getCarbonAppUploaderStub(String username,
String pwd, String url) throws Exception {
CarbonAppUploaderStub carbonAppUploaderStub =
new CarbonAppUploaderStub(url + "/services/CarbonAppUploader");
Header header = createBasicAuthHeader(username, pwd);
List<Header> list = new ArrayList();
list.add(header);
carbonAppUploaderStub._getServiceClient().getOptions()
.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list);
return carbonAppUploaderStub;
}
private ApplicationAdminStub getApplicationAdminStub(String serverURL, String username, String pwd)
throws Exception {
ApplicationAdminStub appAdminStub = new ApplicationAdminStub(serverURL + "/services/ApplicationAdmin");
Header header = createBasicAuthHeader(username, pwd);
List<Header> list = new ArrayList();
list.add(header);
appAdminStub._getServiceClient().getOptions()
.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list);
return appAdminStub;
}
private Header createBasicAuthHeader(String userName, String password) {
| // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public class Constants {
//
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
// public static final int CLIENT_READ_TIMEOUT = 5000;
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
// public static final String MI_SERVER = "mi";
// public static final String EI_SERVER = "ei";
//
// public static final String AUTHORIZATION_HEADER = "Authorization";
// public static final String BASIC = "Basic ";
// public static final String ACCESS_TOKEN = "AccessToken";
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/EICAppHandler.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.activation.DataHandler;
import org.apache.axiom.util.base64.Base64Utils;
import org.apache.commons.httpclient.Header;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.wso2.carbon.application.mgt.stub.upload.types.carbon.UploadedFileItem;
import org.wso2.carbon.stub.ApplicationAdminStub;
import org.wso2.carbon.stub.CarbonAppUploaderStub;
import org.wso2.maven.car.artifact.util.Constants;
import java.io.File;
}
}
private CarbonAppUploaderStub getCarbonAppUploaderStub(String username,
String pwd, String url) throws Exception {
CarbonAppUploaderStub carbonAppUploaderStub =
new CarbonAppUploaderStub(url + "/services/CarbonAppUploader");
Header header = createBasicAuthHeader(username, pwd);
List<Header> list = new ArrayList();
list.add(header);
carbonAppUploaderStub._getServiceClient().getOptions()
.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list);
return carbonAppUploaderStub;
}
private ApplicationAdminStub getApplicationAdminStub(String serverURL, String username, String pwd)
throws Exception {
ApplicationAdminStub appAdminStub = new ApplicationAdminStub(serverURL + "/services/ApplicationAdmin");
Header header = createBasicAuthHeader(username, pwd);
List<Header> list = new ArrayList();
list.add(header);
appAdminStub._getServiceClient().getOptions()
.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list);
return appAdminStub;
}
private Header createBasicAuthHeader(String userName, String password) {
| return new Header(Constants.AUTHORIZATION_HEADER, |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/MICAppHandler.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/CAppMgtApiHelperServiceImpl.java
// public class CAppMgtApiHelperServiceImpl implements CAppMgtApiHelperService {
//
// private String getAsString(InputStream inputStream) throws IOException {
// return IOUtils.toString(inputStream);
// }
//
// @Override
// public JSONObject doAuthenticate(String serverUrl, String username, String password)
// throws CAppMgtServiceStubException {
// try {
// Response response = HTTPSClientUtil.doAuthenticate(serverUrl, username, password);
// if (response.status() == 200 && response.body() != null) {
// return new JSONObject(getAsString(response.body().asInputStream()));
// }
// throw new CAppMgtServiceStubException("Failed to authenticate. " + response.reason());
// } catch (RetryableException e) {
// throw new CAppMgtServiceStubException (
// String.format("Cannot connect to the server node %s.", serverUrl), e);
// } catch (IOException e) {
// throw new CAppMgtServiceStubException ("Failed to read the response body.", e);
// }
// }
//
// @Override
// public boolean deployCApp(File capp, String accessToken, String serverUrl) throws CAppMgtServiceStubException {
// try {
// Response response = HTTPSClientUtil.deployCApp(capp, accessToken, serverUrl);
// if (response.status() == 200) {
// return true;
// }
// throw new CAppMgtServiceStubException("Could not deploy the capp to the server." + response.reason());
// } catch (RetryableException e) {
// throw new CAppMgtServiceStubException (
// String.format("Cannot connect to the server node %s.", serverUrl), e);
// }
// }
//
// @Override
// public boolean unDeployCApp(String accessToken, String serverUrl, String cAppName)
// throws CAppMgtServiceStubException {
// try {
// Response response = HTTPSClientUtil.unDeployCApp(accessToken, serverUrl, cAppName);
// if (response.status() == 200) {
// return true;
// }
// throw new CAppMgtServiceStubException("Could not unDeploy the capp to the server." + response.reason());
// } catch (RetryableException e) {
// throw new CAppMgtServiceStubException (
// String.format("Cannot connect to the server node %s.", serverUrl), e);
// }
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public class Constants {
//
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
// public static final int CLIENT_READ_TIMEOUT = 5000;
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
// public static final String MI_SERVER = "mi";
// public static final String EI_SERVER = "ei";
//
// public static final String AUTHORIZATION_HEADER = "Authorization";
// public static final String BASIC = "Basic ";
// public static final String ACCESS_TOKEN = "AccessToken";
// }
| import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.impl.CAppMgtApiHelperServiceImpl;
import org.wso2.maven.car.artifact.util.Constants;
import java.io.File; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact;
/**
* This class implements CAppHandler to implement the CApp deploy/undeploy logic for MI Servers.
*/
public class MICAppHandler implements CAppHandler {
private final CAppMgtApiHelperServiceImpl capppMgtApiHelperServiceImpl;
private final Log logger;
public MICAppHandler(Log logger) {
this.logger = logger;
this.capppMgtApiHelperServiceImpl = new CAppMgtApiHelperServiceImpl();
}
@Override
public void deployCApp(String username, String password, String serverUrl, File carFile) throws Exception {
JSONObject resObj = capppMgtApiHelperServiceImpl.doAuthenticate(serverUrl, username, password);
if (resObj != null) {
logger.info("Authentication to " + serverUrl + " successful."); | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/CAppMgtApiHelperServiceImpl.java
// public class CAppMgtApiHelperServiceImpl implements CAppMgtApiHelperService {
//
// private String getAsString(InputStream inputStream) throws IOException {
// return IOUtils.toString(inputStream);
// }
//
// @Override
// public JSONObject doAuthenticate(String serverUrl, String username, String password)
// throws CAppMgtServiceStubException {
// try {
// Response response = HTTPSClientUtil.doAuthenticate(serverUrl, username, password);
// if (response.status() == 200 && response.body() != null) {
// return new JSONObject(getAsString(response.body().asInputStream()));
// }
// throw new CAppMgtServiceStubException("Failed to authenticate. " + response.reason());
// } catch (RetryableException e) {
// throw new CAppMgtServiceStubException (
// String.format("Cannot connect to the server node %s.", serverUrl), e);
// } catch (IOException e) {
// throw new CAppMgtServiceStubException ("Failed to read the response body.", e);
// }
// }
//
// @Override
// public boolean deployCApp(File capp, String accessToken, String serverUrl) throws CAppMgtServiceStubException {
// try {
// Response response = HTTPSClientUtil.deployCApp(capp, accessToken, serverUrl);
// if (response.status() == 200) {
// return true;
// }
// throw new CAppMgtServiceStubException("Could not deploy the capp to the server." + response.reason());
// } catch (RetryableException e) {
// throw new CAppMgtServiceStubException (
// String.format("Cannot connect to the server node %s.", serverUrl), e);
// }
// }
//
// @Override
// public boolean unDeployCApp(String accessToken, String serverUrl, String cAppName)
// throws CAppMgtServiceStubException {
// try {
// Response response = HTTPSClientUtil.unDeployCApp(accessToken, serverUrl, cAppName);
// if (response.status() == 200) {
// return true;
// }
// throw new CAppMgtServiceStubException("Could not unDeploy the capp to the server." + response.reason());
// } catch (RetryableException e) {
// throw new CAppMgtServiceStubException (
// String.format("Cannot connect to the server node %s.", serverUrl), e);
// }
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public class Constants {
//
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
// public static final int CLIENT_READ_TIMEOUT = 5000;
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
// public static final String MI_SERVER = "mi";
// public static final String EI_SERVER = "ei";
//
// public static final String AUTHORIZATION_HEADER = "Authorization";
// public static final String BASIC = "Basic ";
// public static final String ACCESS_TOKEN = "AccessToken";
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/MICAppHandler.java
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.impl.CAppMgtApiHelperServiceImpl;
import org.wso2.maven.car.artifact.util.Constants;
import java.io.File;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact;
/**
* This class implements CAppHandler to implement the CApp deploy/undeploy logic for MI Servers.
*/
public class MICAppHandler implements CAppHandler {
private final CAppMgtApiHelperServiceImpl capppMgtApiHelperServiceImpl;
private final Log logger;
public MICAppHandler(Log logger) {
this.logger = logger;
this.capppMgtApiHelperServiceImpl = new CAppMgtApiHelperServiceImpl();
}
@Override
public void deployCApp(String username, String password, String serverUrl, File carFile) throws Exception {
JSONObject resObj = capppMgtApiHelperServiceImpl.doAuthenticate(serverUrl, username, password);
if (resObj != null) {
logger.info("Authentication to " + serverUrl + " successful."); | String accessToken = resObj.getString(Constants.ACCESS_TOKEN); |
wso2/maven-tools | org.wso2.maven.general/src/main/java/org/wso2/maven/registry/RegistryInfo.java | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
| import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the registry-info.xml file which is getting packed inside the carbon application.
* <resources>
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </resources>
* or
* </resources>
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* <resources>
* Oct 15, 2020
*/
public class RegistryInfo extends RegistryInfoProvider {
private List<RegistryElement> registryArtifacts = new ArrayList<RegistryElement>();
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ITEM);
for (OMElement omElement : artifactElements) { | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/RegistryInfo.java
import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the registry-info.xml file which is getting packed inside the carbon application.
* <resources>
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </resources>
* or
* </resources>
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* <resources>
* Oct 15, 2020
*/
public class RegistryInfo extends RegistryInfoProvider {
private List<RegistryElement> registryArtifacts = new ArrayList<RegistryElement>();
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ITEM);
for (OMElement omElement : artifactElements) { | RegistryItem item = getRegistryItem(omElement); |
wso2/maven-tools | org.wso2.maven.general/src/main/java/org/wso2/maven/registry/RegistryInfo.java | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
| import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the registry-info.xml file which is getting packed inside the carbon application.
* <resources>
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </resources>
* or
* </resources>
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* <resources>
* Oct 15, 2020
*/
public class RegistryInfo extends RegistryInfoProvider {
private List<RegistryElement> registryArtifacts = new ArrayList<RegistryElement>();
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ITEM);
for (OMElement omElement : artifactElements) {
RegistryItem item = getRegistryItem(omElement);
registryArtifacts.add(item);
}
List<OMElement> itemElements1 = getChildElements(documentElement, COLLECTION);
for (OMElement omElement2 : itemElements1) { | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/RegistryInfo.java
import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the registry-info.xml file which is getting packed inside the carbon application.
* <resources>
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </resources>
* or
* </resources>
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* <resources>
* Oct 15, 2020
*/
public class RegistryInfo extends RegistryInfoProvider {
private List<RegistryElement> registryArtifacts = new ArrayList<RegistryElement>();
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ITEM);
for (OMElement omElement : artifactElements) {
RegistryItem item = getRegistryItem(omElement);
registryArtifacts.add(item);
}
List<OMElement> itemElements1 = getChildElements(documentElement, COLLECTION);
for (OMElement omElement2 : itemElements1) { | RegistryCollection item = getRegistryCollection(omElement2); |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
| import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List; | if (finalNameNode != null) {
finalName = finalNameNode.getValue();
getLog().info("Final Name of C-App: " + finalName + EXTENSION_CAR);
}
break;
}
}
File carFile = null;
if (null != archiveLocation) { // If default target location is changed by user
if (archiveLocation.isFile() && archiveLocation.getName().endsWith(EXTENSION_CAR)) {
carFile = archiveLocation;
} else {
throw new MojoExecutionException("Archive location is not a valid file");
}
} else { // Default target file
if (finalName == null) {
carFile = new File(target + File.separator + project.getArtifactId() + "_" +
project.getVersion() + EXTENSION_CAR);
} else {
carFile = new File(target + File.separator + finalName + EXTENSION_CAR);
}
}
if (isValidServerType()) {
cAppHandler = getCAppHandler();
} else {
throw new MojoExecutionException("Unsupported serverType. Only allows \"mi\" or \"ei\" ");
}
| // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List;
if (finalNameNode != null) {
finalName = finalNameNode.getValue();
getLog().info("Final Name of C-App: " + finalName + EXTENSION_CAR);
}
break;
}
}
File carFile = null;
if (null != archiveLocation) { // If default target location is changed by user
if (archiveLocation.isFile() && archiveLocation.getName().endsWith(EXTENSION_CAR)) {
carFile = archiveLocation;
} else {
throw new MojoExecutionException("Archive location is not a valid file");
}
} else { // Default target file
if (finalName == null) {
carFile = new File(target + File.separator + project.getArtifactId() + "_" +
project.getVersion() + EXTENSION_CAR);
} else {
carFile = new File(target + File.separator + finalName + EXTENSION_CAR);
}
}
if (isValidServerType()) {
cAppHandler = getCAppHandler();
} else {
throw new MojoExecutionException("Unsupported serverType. Only allows \"mi\" or \"ei\" ");
}
| if (operation.equalsIgnoreCase(CONFIG_OPERATION_DEPLOY)) { |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
| import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List; |
File carFile = null;
if (null != archiveLocation) { // If default target location is changed by user
if (archiveLocation.isFile() && archiveLocation.getName().endsWith(EXTENSION_CAR)) {
carFile = archiveLocation;
} else {
throw new MojoExecutionException("Archive location is not a valid file");
}
} else { // Default target file
if (finalName == null) {
carFile = new File(target + File.separator + project.getArtifactId() + "_" +
project.getVersion() + EXTENSION_CAR);
} else {
carFile = new File(target + File.separator + finalName + EXTENSION_CAR);
}
}
if (isValidServerType()) {
cAppHandler = getCAppHandler();
} else {
throw new MojoExecutionException("Unsupported serverType. Only allows \"mi\" or \"ei\" ");
}
if (operation.equalsIgnoreCase(CONFIG_OPERATION_DEPLOY)) {
try {
cAppHandler.deployCApp(userName, password, serverUrl, carFile);
} catch (Exception e) {
getLog().error("Uploading " + carFile.getName() + " to " + serverUrl + " Failed.", e);
throw new MojoExecutionException("Deploying " + carFile.getName() + " to " + serverUrl + " Failed.", e);
} | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List;
File carFile = null;
if (null != archiveLocation) { // If default target location is changed by user
if (archiveLocation.isFile() && archiveLocation.getName().endsWith(EXTENSION_CAR)) {
carFile = archiveLocation;
} else {
throw new MojoExecutionException("Archive location is not a valid file");
}
} else { // Default target file
if (finalName == null) {
carFile = new File(target + File.separator + project.getArtifactId() + "_" +
project.getVersion() + EXTENSION_CAR);
} else {
carFile = new File(target + File.separator + finalName + EXTENSION_CAR);
}
}
if (isValidServerType()) {
cAppHandler = getCAppHandler();
} else {
throw new MojoExecutionException("Unsupported serverType. Only allows \"mi\" or \"ei\" ");
}
if (operation.equalsIgnoreCase(CONFIG_OPERATION_DEPLOY)) {
try {
cAppHandler.deployCApp(userName, password, serverUrl, carFile);
} catch (Exception e) {
getLog().error("Uploading " + carFile.getName() + " to " + serverUrl + " Failed.", e);
throw new MojoExecutionException("Deploying " + carFile.getName() + " to " + serverUrl + " Failed.", e);
} | } else if (operation.equalsIgnoreCase(CONFIG_OPERATION_UNDEPLOY)) { |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
| import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List; | }
@SuppressWarnings("unused")
private void printParams() {
if (!carbonServers.isEmpty()) {
for (CarbonServer server : carbonServers) {
getLog().info("Server:");
getLog().info("TSPath=" + server.getTrustStorePath());
getLog().info("TSPWD=" + server.getTrustStorePassword());
getLog().info("TSType=" + server.getTrustStoreType());
getLog().info("Server URL=" + server.getServerUrl());
getLog().info("Operation=" + server.getOperation());
if (server.getUserName() == null) {
getLog().info("Please enter a valid user name.");
}
}
}
}
private void setSystemProperties() {
System.setProperty("javax.net.ssl.trustStore", trustStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
}
private boolean isValidServerType() {
| // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List;
}
@SuppressWarnings("unused")
private void printParams() {
if (!carbonServers.isEmpty()) {
for (CarbonServer server : carbonServers) {
getLog().info("Server:");
getLog().info("TSPath=" + server.getTrustStorePath());
getLog().info("TSPWD=" + server.getTrustStorePassword());
getLog().info("TSType=" + server.getTrustStoreType());
getLog().info("Server URL=" + server.getServerUrl());
getLog().info("Operation=" + server.getOperation());
if (server.getUserName() == null) {
getLog().info("Please enter a valid user name.");
}
}
}
}
private void setSystemProperties() {
System.setProperty("javax.net.ssl.trustStore", trustStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
}
private boolean isValidServerType() {
| return serverType.equalsIgnoreCase(MI_SERVER) || serverType.equalsIgnoreCase(EI_SERVER); |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
| import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List; | }
@SuppressWarnings("unused")
private void printParams() {
if (!carbonServers.isEmpty()) {
for (CarbonServer server : carbonServers) {
getLog().info("Server:");
getLog().info("TSPath=" + server.getTrustStorePath());
getLog().info("TSPWD=" + server.getTrustStorePassword());
getLog().info("TSType=" + server.getTrustStoreType());
getLog().info("Server URL=" + server.getServerUrl());
getLog().info("Operation=" + server.getOperation());
if (server.getUserName() == null) {
getLog().info("Please enter a valid user name.");
}
}
}
}
private void setSystemProperties() {
System.setProperty("javax.net.ssl.trustStore", trustStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
}
private boolean isValidServerType() {
| // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_DEPLOY = "deploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String CONFIG_OPERATION_UNDEPLOY = "undeploy";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String EI_SERVER = "ei";
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final String MI_SERVER = "mi";
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/DeployCarMojo.java
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_DEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.CONFIG_OPERATION_UNDEPLOY;
import static org.wso2.maven.car.artifact.util.Constants.EI_SERVER;
import static org.wso2.maven.car.artifact.util.Constants.MI_SERVER;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.File;
import java.util.List;
}
@SuppressWarnings("unused")
private void printParams() {
if (!carbonServers.isEmpty()) {
for (CarbonServer server : carbonServers) {
getLog().info("Server:");
getLog().info("TSPath=" + server.getTrustStorePath());
getLog().info("TSPWD=" + server.getTrustStorePassword());
getLog().info("TSType=" + server.getTrustStoreType());
getLog().info("Server URL=" + server.getServerUrl());
getLog().info("Operation=" + server.getOperation());
if (server.getUserName() == null) {
getLog().info("Please enter a valid user name.");
}
}
}
}
private void setSystemProperties() {
System.setProperty("javax.net.ssl.trustStore", trustStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
}
private boolean isValidServerType() {
| return serverType.equalsIgnoreCase(MI_SERVER) || serverType.equalsIgnoreCase(EI_SERVER); |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/api/CAppMgtApiHelperService.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import java.io.File;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.api;
/**
* Describes methods that communicate with the MI server.
*/
public interface CAppMgtApiHelperService {
JSONObject doAuthenticate(String serverUrl, String username, String password) | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/api/CAppMgtApiHelperService.java
import java.io.File;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.api;
/**
* Describes methods that communicate with the MI server.
*/
public interface CAppMgtApiHelperService {
JSONObject doAuthenticate(String serverUrl, String username, String password) | throws CAppMgtServiceStubException; |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/CAppMgtApiHelperServiceImpl.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/api/CAppMgtApiHelperService.java
// public interface CAppMgtApiHelperService {
//
// JSONObject doAuthenticate(String serverUrl, String username, String password)
// throws CAppMgtServiceStubException;
//
// boolean deployCApp(File capp, String accessToken, String serverUrl) throws CAppMgtServiceStubException;
//
// boolean unDeployCApp(String accessToken, String serverUrl, String cAppName)
// throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/HTTPSClientUtil.java
// public class HTTPSClientUtil {
//
// /**
// * Avoids Instantiation.
// */
// private HTTPSClientUtil() {
//
// }
//
// public static Response doAuthenticate(String serverUrl, String username, String password) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient(serverUrl, username, password).doAuthenticate();
// }
//
// public static Response deployCApp(File capp, String accessToken, String serverUrl) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient2(serverUrl, accessToken).deployCApp(capp);
// }
//
// public static Response unDeployCApp(String accessToken, String serverUrl, String cAppName) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient3(serverUrl, accessToken).
// unDeployCApp(cAppName);
// }
//
//
// }
| import java.io.InputStream;
import feign.Response;
import feign.RetryableException;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.api.CAppMgtApiHelperService;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
import org.wso2.maven.car.artifact.util.HTTPSClientUtil;
import java.io.File;
import java.io.IOException; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.impl;
public class CAppMgtApiHelperServiceImpl implements CAppMgtApiHelperService {
private String getAsString(InputStream inputStream) throws IOException {
return IOUtils.toString(inputStream);
}
@Override
public JSONObject doAuthenticate(String serverUrl, String username, String password) | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/api/CAppMgtApiHelperService.java
// public interface CAppMgtApiHelperService {
//
// JSONObject doAuthenticate(String serverUrl, String username, String password)
// throws CAppMgtServiceStubException;
//
// boolean deployCApp(File capp, String accessToken, String serverUrl) throws CAppMgtServiceStubException;
//
// boolean unDeployCApp(String accessToken, String serverUrl, String cAppName)
// throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/HTTPSClientUtil.java
// public class HTTPSClientUtil {
//
// /**
// * Avoids Instantiation.
// */
// private HTTPSClientUtil() {
//
// }
//
// public static Response doAuthenticate(String serverUrl, String username, String password) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient(serverUrl, username, password).doAuthenticate();
// }
//
// public static Response deployCApp(File capp, String accessToken, String serverUrl) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient2(serverUrl, accessToken).deployCApp(capp);
// }
//
// public static Response unDeployCApp(String accessToken, String serverUrl, String cAppName) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient3(serverUrl, accessToken).
// unDeployCApp(cAppName);
// }
//
//
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/CAppMgtApiHelperServiceImpl.java
import java.io.InputStream;
import feign.Response;
import feign.RetryableException;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.api.CAppMgtApiHelperService;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
import org.wso2.maven.car.artifact.util.HTTPSClientUtil;
import java.io.File;
import java.io.IOException;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.impl;
public class CAppMgtApiHelperServiceImpl implements CAppMgtApiHelperService {
private String getAsString(InputStream inputStream) throws IOException {
return IOUtils.toString(inputStream);
}
@Override
public JSONObject doAuthenticate(String serverUrl, String username, String password) | throws CAppMgtServiceStubException { |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/CAppMgtApiHelperServiceImpl.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/api/CAppMgtApiHelperService.java
// public interface CAppMgtApiHelperService {
//
// JSONObject doAuthenticate(String serverUrl, String username, String password)
// throws CAppMgtServiceStubException;
//
// boolean deployCApp(File capp, String accessToken, String serverUrl) throws CAppMgtServiceStubException;
//
// boolean unDeployCApp(String accessToken, String serverUrl, String cAppName)
// throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/HTTPSClientUtil.java
// public class HTTPSClientUtil {
//
// /**
// * Avoids Instantiation.
// */
// private HTTPSClientUtil() {
//
// }
//
// public static Response doAuthenticate(String serverUrl, String username, String password) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient(serverUrl, username, password).doAuthenticate();
// }
//
// public static Response deployCApp(File capp, String accessToken, String serverUrl) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient2(serverUrl, accessToken).deployCApp(capp);
// }
//
// public static Response unDeployCApp(String accessToken, String serverUrl, String cAppName) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient3(serverUrl, accessToken).
// unDeployCApp(cAppName);
// }
//
//
// }
| import java.io.InputStream;
import feign.Response;
import feign.RetryableException;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.api.CAppMgtApiHelperService;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
import org.wso2.maven.car.artifact.util.HTTPSClientUtil;
import java.io.File;
import java.io.IOException; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.impl;
public class CAppMgtApiHelperServiceImpl implements CAppMgtApiHelperService {
private String getAsString(InputStream inputStream) throws IOException {
return IOUtils.toString(inputStream);
}
@Override
public JSONObject doAuthenticate(String serverUrl, String username, String password)
throws CAppMgtServiceStubException {
try { | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/api/CAppMgtApiHelperService.java
// public interface CAppMgtApiHelperService {
//
// JSONObject doAuthenticate(String serverUrl, String username, String password)
// throws CAppMgtServiceStubException;
//
// boolean deployCApp(File capp, String accessToken, String serverUrl) throws CAppMgtServiceStubException;
//
// boolean unDeployCApp(String accessToken, String serverUrl, String cAppName)
// throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/exception/CAppMgtServiceStubException.java
// public class CAppMgtServiceStubException extends Exception {
//
// public CAppMgtServiceStubException(String message) {
// super(message);
// }
//
// public CAppMgtServiceStubException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/HTTPSClientUtil.java
// public class HTTPSClientUtil {
//
// /**
// * Avoids Instantiation.
// */
// private HTTPSClientUtil() {
//
// }
//
// public static Response doAuthenticate(String serverUrl, String username, String password) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient(serverUrl, username, password).doAuthenticate();
// }
//
// public static Response deployCApp(File capp, String accessToken, String serverUrl) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient2(serverUrl, accessToken).deployCApp(capp);
// }
//
// public static Response unDeployCApp(String accessToken, String serverUrl, String cAppName) throws
// CAppMgtServiceStubException{
// return CAppMgtHandlerFactory.getCAppMgtHttpsClient3(serverUrl, accessToken).
// unDeployCApp(cAppName);
// }
//
//
// }
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/CAppMgtApiHelperServiceImpl.java
import java.io.InputStream;
import feign.Response;
import feign.RetryableException;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.wso2.maven.car.artifact.api.CAppMgtApiHelperService;
import org.wso2.maven.car.artifact.exception.CAppMgtServiceStubException;
import org.wso2.maven.car.artifact.util.HTTPSClientUtil;
import java.io.File;
import java.io.IOException;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.impl;
public class CAppMgtApiHelperServiceImpl implements CAppMgtApiHelperService {
private String getAsString(InputStream inputStream) throws IOException {
return IOUtils.toString(inputStream);
}
@Override
public JSONObject doAuthenticate(String serverUrl, String username, String password)
throws CAppMgtServiceStubException {
try { | Response response = HTTPSClientUtil.doAuthenticate(serverUrl, username, password); |
wso2/maven-tools | org.wso2.maven.general/src/main/java/org/wso2/maven/registry/RegistryArtifact.java | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
| import org.wso2.maven.registry.beans.RegistryElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
public class RegistryArtifact {
private String name;
private String version;
private String serverRole;
private String type;
private String groupId;
// This is the file path for the actual artifact.
// <artifact name="testEndpoint3" version="1.0.0" type="synapse/endpoint" serverRole="EnterpriseServiceBus">
// <file>src\main\synapse-config\endpoints\testEndpoint3.xml</file>
// </artifact>
| // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/RegistryArtifact.java
import org.wso2.maven.registry.beans.RegistryElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
public class RegistryArtifact {
private String name;
private String version;
private String serverRole;
private String type;
private String groupId;
// This is the file path for the actual artifact.
// <artifact name="testEndpoint3" version="1.0.0" type="synapse/endpoint" serverRole="EnterpriseServiceBus">
// <file>src\main\synapse-config\endpoints\testEndpoint3.xml</file>
// </artifact>
| private List<RegistryElement> items = new ArrayList<RegistryElement>(); |
wso2/maven-tools | vscode-car-plugin/src/main/java/org/wso2/maven/CARMojo.java | // Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArchiveException.java
// public class ArchiveException extends Exception {
// public ArchiveException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArtifactDependency.java
// public class ArtifactDependency {
// private String artifact;
// private String version;
// private String serverRole;
// private Boolean include;
//
// public ArtifactDependency(String artifact, String version, String serverRole, Boolean include) {
// this.artifact = artifact;
// this.version = version;
// this.serverRole = serverRole;
// this.include = include;
// }
//
// /**
// * @return the artifact
// */
// public String getArtifact() {
// return artifact;
// }
//
// /**
// * @param artifact of the dependency
// */
// public void setArtifact(String artifact) {
// this.artifact = artifact;
// }
//
// /**
// * @return the verison
// */
// public String getVersion() {
// return version;
// }
//
// /**
// * @param version of the dependency
// */
// public void setVersion(String version) {
// this.version = version;
// }
//
// /**
// * @return the serverRole
// */
// public String getServerRole() {
// return serverRole;
// }
//
// /**
// * @param serverRole of the dependency
// */
// public void setServerRole(String serverRole) {
// this.serverRole = serverRole;
// }
//
// /**
// * @return include
// */
// public Boolean getInclude() {
// return include;
// }
//
// /**
// * @param include of the dependency
// */
// public void setInclude(Boolean include) {
// this.include = include;
// }
// }
| import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
import org.wso2.maven.Model.ArchiveException;
import org.wso2.maven.Model.ArtifactDependency;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.stream.XMLStreamException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException; | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.maven;
/**
* Goal which touches a timestamp file.
*
* @goal car
* @phase package
*/
@Mojo(name = "WSO2ESBDeployableArchive")
public class CARMojo extends AbstractMojo {
/**
* Location of the default build folder.
*
* @parameter expression="${project.build.directory}"
*/
private File projectBuildDir;
/**
* Location of the archive folder.
*
* @parameter expression="${project.build.directory}"
*/
private File archiveLocation;
/**
* archiveName is used if the user wants to override the default name of the generated archive with .car extension.
*
* @parameter expression="${project.build.archiveName}"
*/
private String archiveName;
/**
* CarbonApp is used if the user wants to override the default name of the carbon application.
*
* @parameter
*/
private String cAppName;
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/**
* A classifier for the build final name.
*
* @parameter
*/
private String classifier;
/**
* Read artifact.xml files and create .car file.
*/
public void execute() throws MojoExecutionException {
appendLogs();
// Create CApp
try {
// Create directory to be compressed.
String archiveDirectory = getArchiveFile(Constants.EMPTY_STRING).getAbsolutePath();
boolean createdArchiveDirectory = org.wso2.developerstudio.eclipse.utils.file.FileUtils.createDirectories(
archiveDirectory);
if (createdArchiveDirectory) {
CAppHandler cAppHandler = new CAppHandler(cAppName); | // Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArchiveException.java
// public class ArchiveException extends Exception {
// public ArchiveException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArtifactDependency.java
// public class ArtifactDependency {
// private String artifact;
// private String version;
// private String serverRole;
// private Boolean include;
//
// public ArtifactDependency(String artifact, String version, String serverRole, Boolean include) {
// this.artifact = artifact;
// this.version = version;
// this.serverRole = serverRole;
// this.include = include;
// }
//
// /**
// * @return the artifact
// */
// public String getArtifact() {
// return artifact;
// }
//
// /**
// * @param artifact of the dependency
// */
// public void setArtifact(String artifact) {
// this.artifact = artifact;
// }
//
// /**
// * @return the verison
// */
// public String getVersion() {
// return version;
// }
//
// /**
// * @param version of the dependency
// */
// public void setVersion(String version) {
// this.version = version;
// }
//
// /**
// * @return the serverRole
// */
// public String getServerRole() {
// return serverRole;
// }
//
// /**
// * @param serverRole of the dependency
// */
// public void setServerRole(String serverRole) {
// this.serverRole = serverRole;
// }
//
// /**
// * @return include
// */
// public Boolean getInclude() {
// return include;
// }
//
// /**
// * @param include of the dependency
// */
// public void setInclude(Boolean include) {
// this.include = include;
// }
// }
// Path: vscode-car-plugin/src/main/java/org/wso2/maven/CARMojo.java
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
import org.wso2.maven.Model.ArchiveException;
import org.wso2.maven.Model.ArtifactDependency;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.stream.XMLStreamException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.maven;
/**
* Goal which touches a timestamp file.
*
* @goal car
* @phase package
*/
@Mojo(name = "WSO2ESBDeployableArchive")
public class CARMojo extends AbstractMojo {
/**
* Location of the default build folder.
*
* @parameter expression="${project.build.directory}"
*/
private File projectBuildDir;
/**
* Location of the archive folder.
*
* @parameter expression="${project.build.directory}"
*/
private File archiveLocation;
/**
* archiveName is used if the user wants to override the default name of the generated archive with .car extension.
*
* @parameter expression="${project.build.archiveName}"
*/
private String archiveName;
/**
* CarbonApp is used if the user wants to override the default name of the carbon application.
*
* @parameter
*/
private String cAppName;
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/**
* A classifier for the build final name.
*
* @parameter
*/
private String classifier;
/**
* Read artifact.xml files and create .car file.
*/
public void execute() throws MojoExecutionException {
appendLogs();
// Create CApp
try {
// Create directory to be compressed.
String archiveDirectory = getArchiveFile(Constants.EMPTY_STRING).getAbsolutePath();
boolean createdArchiveDirectory = org.wso2.developerstudio.eclipse.utils.file.FileUtils.createDirectories(
archiveDirectory);
if (createdArchiveDirectory) {
CAppHandler cAppHandler = new CAppHandler(cAppName); | List<ArtifactDependency> dependencies = new ArrayList<>(); |
wso2/maven-tools | vscode-car-plugin/src/main/java/org/wso2/maven/CARMojo.java | // Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArchiveException.java
// public class ArchiveException extends Exception {
// public ArchiveException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArtifactDependency.java
// public class ArtifactDependency {
// private String artifact;
// private String version;
// private String serverRole;
// private Boolean include;
//
// public ArtifactDependency(String artifact, String version, String serverRole, Boolean include) {
// this.artifact = artifact;
// this.version = version;
// this.serverRole = serverRole;
// this.include = include;
// }
//
// /**
// * @return the artifact
// */
// public String getArtifact() {
// return artifact;
// }
//
// /**
// * @param artifact of the dependency
// */
// public void setArtifact(String artifact) {
// this.artifact = artifact;
// }
//
// /**
// * @return the verison
// */
// public String getVersion() {
// return version;
// }
//
// /**
// * @param version of the dependency
// */
// public void setVersion(String version) {
// this.version = version;
// }
//
// /**
// * @return the serverRole
// */
// public String getServerRole() {
// return serverRole;
// }
//
// /**
// * @param serverRole of the dependency
// */
// public void setServerRole(String serverRole) {
// this.serverRole = serverRole;
// }
//
// /**
// * @return include
// */
// public Boolean getInclude() {
// return include;
// }
//
// /**
// * @param include of the dependency
// */
// public void setInclude(Boolean include) {
// this.include = include;
// }
// }
| import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
import org.wso2.maven.Model.ArchiveException;
import org.wso2.maven.Model.ArtifactDependency;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.stream.XMLStreamException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException; | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.maven;
/**
* Goal which touches a timestamp file.
*
* @goal car
* @phase package
*/
@Mojo(name = "WSO2ESBDeployableArchive")
public class CARMojo extends AbstractMojo {
/**
* Location of the default build folder.
*
* @parameter expression="${project.build.directory}"
*/
private File projectBuildDir;
/**
* Location of the archive folder.
*
* @parameter expression="${project.build.directory}"
*/
private File archiveLocation;
/**
* archiveName is used if the user wants to override the default name of the generated archive with .car extension.
*
* @parameter expression="${project.build.archiveName}"
*/
private String archiveName;
/**
* CarbonApp is used if the user wants to override the default name of the carbon application.
*
* @parameter
*/
private String cAppName;
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/**
* A classifier for the build final name.
*
* @parameter
*/
private String classifier;
/**
* Read artifact.xml files and create .car file.
*/
public void execute() throws MojoExecutionException {
appendLogs();
// Create CApp
try {
// Create directory to be compressed.
String archiveDirectory = getArchiveFile(Constants.EMPTY_STRING).getAbsolutePath();
boolean createdArchiveDirectory = org.wso2.developerstudio.eclipse.utils.file.FileUtils.createDirectories(
archiveDirectory);
if (createdArchiveDirectory) {
CAppHandler cAppHandler = new CAppHandler(cAppName);
List<ArtifactDependency> dependencies = new ArrayList<>();
cAppHandler.processConfigArtifactXmlFile(projectBuildDir, archiveDirectory, dependencies);
cAppHandler.processRegistryResourceArtifactXmlFile(projectBuildDir, archiveDirectory, dependencies);
cAppHandler.createDependencyArtifactsXmlFile(archiveDirectory, dependencies, project);
File fileToZip = new File(archiveDirectory);
File carFile = getArchiveFile(".car");
zipFolder(fileToZip.getPath(), carFile.getPath());
// Attach carFile to Maven context.
this.project.getArtifact().setFile(carFile);
recursiveDelete(fileToZip);
} else {
getLog().error("Could not create corresponding archive directory.");
} | // Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArchiveException.java
// public class ArchiveException extends Exception {
// public ArchiveException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: vscode-car-plugin/src/main/java/org/wso2/maven/Model/ArtifactDependency.java
// public class ArtifactDependency {
// private String artifact;
// private String version;
// private String serverRole;
// private Boolean include;
//
// public ArtifactDependency(String artifact, String version, String serverRole, Boolean include) {
// this.artifact = artifact;
// this.version = version;
// this.serverRole = serverRole;
// this.include = include;
// }
//
// /**
// * @return the artifact
// */
// public String getArtifact() {
// return artifact;
// }
//
// /**
// * @param artifact of the dependency
// */
// public void setArtifact(String artifact) {
// this.artifact = artifact;
// }
//
// /**
// * @return the verison
// */
// public String getVersion() {
// return version;
// }
//
// /**
// * @param version of the dependency
// */
// public void setVersion(String version) {
// this.version = version;
// }
//
// /**
// * @return the serverRole
// */
// public String getServerRole() {
// return serverRole;
// }
//
// /**
// * @param serverRole of the dependency
// */
// public void setServerRole(String serverRole) {
// this.serverRole = serverRole;
// }
//
// /**
// * @return include
// */
// public Boolean getInclude() {
// return include;
// }
//
// /**
// * @param include of the dependency
// */
// public void setInclude(Boolean include) {
// this.include = include;
// }
// }
// Path: vscode-car-plugin/src/main/java/org/wso2/maven/CARMojo.java
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
import org.wso2.maven.Model.ArchiveException;
import org.wso2.maven.Model.ArtifactDependency;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.stream.XMLStreamException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.maven;
/**
* Goal which touches a timestamp file.
*
* @goal car
* @phase package
*/
@Mojo(name = "WSO2ESBDeployableArchive")
public class CARMojo extends AbstractMojo {
/**
* Location of the default build folder.
*
* @parameter expression="${project.build.directory}"
*/
private File projectBuildDir;
/**
* Location of the archive folder.
*
* @parameter expression="${project.build.directory}"
*/
private File archiveLocation;
/**
* archiveName is used if the user wants to override the default name of the generated archive with .car extension.
*
* @parameter expression="${project.build.archiveName}"
*/
private String archiveName;
/**
* CarbonApp is used if the user wants to override the default name of the carbon application.
*
* @parameter
*/
private String cAppName;
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/**
* A classifier for the build final name.
*
* @parameter
*/
private String classifier;
/**
* Read artifact.xml files and create .car file.
*/
public void execute() throws MojoExecutionException {
appendLogs();
// Create CApp
try {
// Create directory to be compressed.
String archiveDirectory = getArchiveFile(Constants.EMPTY_STRING).getAbsolutePath();
boolean createdArchiveDirectory = org.wso2.developerstudio.eclipse.utils.file.FileUtils.createDirectories(
archiveDirectory);
if (createdArchiveDirectory) {
CAppHandler cAppHandler = new CAppHandler(cAppName);
List<ArtifactDependency> dependencies = new ArrayList<>();
cAppHandler.processConfigArtifactXmlFile(projectBuildDir, archiveDirectory, dependencies);
cAppHandler.processRegistryResourceArtifactXmlFile(projectBuildDir, archiveDirectory, dependencies);
cAppHandler.createDependencyArtifactsXmlFile(archiveDirectory, dependencies, project);
File fileToZip = new File(archiveDirectory);
File carFile = getArchiveFile(".car");
zipFolder(fileToZip.getPath(), carFile.getPath());
// Attach carFile to Maven context.
this.project.getArtifact().setFile(carFile);
recursiveDelete(fileToZip);
} else {
getLog().error("Could not create corresponding archive directory.");
} | } catch (XMLStreamException | IOException | ArchiveException e) { |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/CAppMgtHandlerFactory.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
// public interface CAppMgtServiceStub {
//
// @RequestLine("GET /management/login")
// @Headers("accept: application/json; charset=utf-8")
// Response doAuthenticate() throws CAppMgtServiceStubException;
//
// @RequestLine("POST /management/applications")
// @Headers("Content-Type: multipart/form-data; charset=utf-8")
// Response deployCApp(@Param("file") File capp) throws CAppMgtServiceStubException;
//
// @RequestLine("DELETE /management/applications/{name}")
// @Headers("Content-Type: application/json; charset=utf-8")
// Response unDeployCApp(@Param("name") String cAppName) throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/HTTPClientBuilderServiceImpl.java
// public class HTTPClientBuilderServiceImpl implements HTTPClientBuilderService {
//
// public Client newDefaultClientInstance() {
// return new Client.Default(null, null);
// }
//
// @Override
// public <T> T buildWithBasicAuth(String username, String password, int connectTimeoutMillis, int readTimeoutMillis,
// Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new BasicAuthRequestInterceptor(username, password))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWTAndFormEncoder(String accessToken, int connectTimeoutMillis,
// int readTimeoutMillis, Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new FormEncoder())
// .decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWT(String accessToken, int connectTimeoutMillis, int readTimeoutMillis, Class<T> target,
// String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_READ_TIMEOUT = 5000;
| import static org.wso2.maven.car.artifact.util.Constants.CLIENT_CONNECTION_TIMEOUT;
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_READ_TIMEOUT;
import org.wso2.maven.car.artifact.CAppMgtServiceStub;
import org.wso2.maven.car.artifact.impl.HTTPClientBuilderServiceImpl; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class CAppMgtHandlerFactory {
private static HTTPClientBuilderServiceImpl instance = new HTTPClientBuilderServiceImpl();
private CAppMgtHandlerFactory(){}
/**
* Returns an HTTPS client for communicating with the MI server with basic auth.
*
* @param serverUrl HTTPS URL of the MI server.
* @param username Username.
* @param password Password.
* @return ErrorHandlerServiceStub instance which functions as the HTTPS client.
*/ | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
// public interface CAppMgtServiceStub {
//
// @RequestLine("GET /management/login")
// @Headers("accept: application/json; charset=utf-8")
// Response doAuthenticate() throws CAppMgtServiceStubException;
//
// @RequestLine("POST /management/applications")
// @Headers("Content-Type: multipart/form-data; charset=utf-8")
// Response deployCApp(@Param("file") File capp) throws CAppMgtServiceStubException;
//
// @RequestLine("DELETE /management/applications/{name}")
// @Headers("Content-Type: application/json; charset=utf-8")
// Response unDeployCApp(@Param("name") String cAppName) throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/HTTPClientBuilderServiceImpl.java
// public class HTTPClientBuilderServiceImpl implements HTTPClientBuilderService {
//
// public Client newDefaultClientInstance() {
// return new Client.Default(null, null);
// }
//
// @Override
// public <T> T buildWithBasicAuth(String username, String password, int connectTimeoutMillis, int readTimeoutMillis,
// Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new BasicAuthRequestInterceptor(username, password))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWTAndFormEncoder(String accessToken, int connectTimeoutMillis,
// int readTimeoutMillis, Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new FormEncoder())
// .decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWT(String accessToken, int connectTimeoutMillis, int readTimeoutMillis, Class<T> target,
// String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_READ_TIMEOUT = 5000;
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/CAppMgtHandlerFactory.java
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_CONNECTION_TIMEOUT;
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_READ_TIMEOUT;
import org.wso2.maven.car.artifact.CAppMgtServiceStub;
import org.wso2.maven.car.artifact.impl.HTTPClientBuilderServiceImpl;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class CAppMgtHandlerFactory {
private static HTTPClientBuilderServiceImpl instance = new HTTPClientBuilderServiceImpl();
private CAppMgtHandlerFactory(){}
/**
* Returns an HTTPS client for communicating with the MI server with basic auth.
*
* @param serverUrl HTTPS URL of the MI server.
* @param username Username.
* @param password Password.
* @return ErrorHandlerServiceStub instance which functions as the HTTPS client.
*/ | public static CAppMgtServiceStub getCAppMgtHttpsClient(String serverUrl, String username, |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/CAppMgtHandlerFactory.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
// public interface CAppMgtServiceStub {
//
// @RequestLine("GET /management/login")
// @Headers("accept: application/json; charset=utf-8")
// Response doAuthenticate() throws CAppMgtServiceStubException;
//
// @RequestLine("POST /management/applications")
// @Headers("Content-Type: multipart/form-data; charset=utf-8")
// Response deployCApp(@Param("file") File capp) throws CAppMgtServiceStubException;
//
// @RequestLine("DELETE /management/applications/{name}")
// @Headers("Content-Type: application/json; charset=utf-8")
// Response unDeployCApp(@Param("name") String cAppName) throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/HTTPClientBuilderServiceImpl.java
// public class HTTPClientBuilderServiceImpl implements HTTPClientBuilderService {
//
// public Client newDefaultClientInstance() {
// return new Client.Default(null, null);
// }
//
// @Override
// public <T> T buildWithBasicAuth(String username, String password, int connectTimeoutMillis, int readTimeoutMillis,
// Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new BasicAuthRequestInterceptor(username, password))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWTAndFormEncoder(String accessToken, int connectTimeoutMillis,
// int readTimeoutMillis, Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new FormEncoder())
// .decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWT(String accessToken, int connectTimeoutMillis, int readTimeoutMillis, Class<T> target,
// String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_READ_TIMEOUT = 5000;
| import static org.wso2.maven.car.artifact.util.Constants.CLIENT_CONNECTION_TIMEOUT;
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_READ_TIMEOUT;
import org.wso2.maven.car.artifact.CAppMgtServiceStub;
import org.wso2.maven.car.artifact.impl.HTTPClientBuilderServiceImpl; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class CAppMgtHandlerFactory {
private static HTTPClientBuilderServiceImpl instance = new HTTPClientBuilderServiceImpl();
private CAppMgtHandlerFactory(){}
/**
* Returns an HTTPS client for communicating with the MI server with basic auth.
*
* @param serverUrl HTTPS URL of the MI server.
* @param username Username.
* @param password Password.
* @return ErrorHandlerServiceStub instance which functions as the HTTPS client.
*/
public static CAppMgtServiceStub getCAppMgtHttpsClient(String serverUrl, String username,
String password) {
return instance.buildWithBasicAuth(username, password, | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
// public interface CAppMgtServiceStub {
//
// @RequestLine("GET /management/login")
// @Headers("accept: application/json; charset=utf-8")
// Response doAuthenticate() throws CAppMgtServiceStubException;
//
// @RequestLine("POST /management/applications")
// @Headers("Content-Type: multipart/form-data; charset=utf-8")
// Response deployCApp(@Param("file") File capp) throws CAppMgtServiceStubException;
//
// @RequestLine("DELETE /management/applications/{name}")
// @Headers("Content-Type: application/json; charset=utf-8")
// Response unDeployCApp(@Param("name") String cAppName) throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/HTTPClientBuilderServiceImpl.java
// public class HTTPClientBuilderServiceImpl implements HTTPClientBuilderService {
//
// public Client newDefaultClientInstance() {
// return new Client.Default(null, null);
// }
//
// @Override
// public <T> T buildWithBasicAuth(String username, String password, int connectTimeoutMillis, int readTimeoutMillis,
// Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new BasicAuthRequestInterceptor(username, password))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWTAndFormEncoder(String accessToken, int connectTimeoutMillis,
// int readTimeoutMillis, Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new FormEncoder())
// .decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWT(String accessToken, int connectTimeoutMillis, int readTimeoutMillis, Class<T> target,
// String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_READ_TIMEOUT = 5000;
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/CAppMgtHandlerFactory.java
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_CONNECTION_TIMEOUT;
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_READ_TIMEOUT;
import org.wso2.maven.car.artifact.CAppMgtServiceStub;
import org.wso2.maven.car.artifact.impl.HTTPClientBuilderServiceImpl;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class CAppMgtHandlerFactory {
private static HTTPClientBuilderServiceImpl instance = new HTTPClientBuilderServiceImpl();
private CAppMgtHandlerFactory(){}
/**
* Returns an HTTPS client for communicating with the MI server with basic auth.
*
* @param serverUrl HTTPS URL of the MI server.
* @param username Username.
* @param password Password.
* @return ErrorHandlerServiceStub instance which functions as the HTTPS client.
*/
public static CAppMgtServiceStub getCAppMgtHttpsClient(String serverUrl, String username,
String password) {
return instance.buildWithBasicAuth(username, password, | CLIENT_CONNECTION_TIMEOUT, CLIENT_READ_TIMEOUT, CAppMgtServiceStub.class, serverUrl); |
wso2/maven-tools | maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/CAppMgtHandlerFactory.java | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
// public interface CAppMgtServiceStub {
//
// @RequestLine("GET /management/login")
// @Headers("accept: application/json; charset=utf-8")
// Response doAuthenticate() throws CAppMgtServiceStubException;
//
// @RequestLine("POST /management/applications")
// @Headers("Content-Type: multipart/form-data; charset=utf-8")
// Response deployCApp(@Param("file") File capp) throws CAppMgtServiceStubException;
//
// @RequestLine("DELETE /management/applications/{name}")
// @Headers("Content-Type: application/json; charset=utf-8")
// Response unDeployCApp(@Param("name") String cAppName) throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/HTTPClientBuilderServiceImpl.java
// public class HTTPClientBuilderServiceImpl implements HTTPClientBuilderService {
//
// public Client newDefaultClientInstance() {
// return new Client.Default(null, null);
// }
//
// @Override
// public <T> T buildWithBasicAuth(String username, String password, int connectTimeoutMillis, int readTimeoutMillis,
// Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new BasicAuthRequestInterceptor(username, password))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWTAndFormEncoder(String accessToken, int connectTimeoutMillis,
// int readTimeoutMillis, Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new FormEncoder())
// .decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWT(String accessToken, int connectTimeoutMillis, int readTimeoutMillis, Class<T> target,
// String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_READ_TIMEOUT = 5000;
| import static org.wso2.maven.car.artifact.util.Constants.CLIENT_CONNECTION_TIMEOUT;
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_READ_TIMEOUT;
import org.wso2.maven.car.artifact.CAppMgtServiceStub;
import org.wso2.maven.car.artifact.impl.HTTPClientBuilderServiceImpl; | /*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class CAppMgtHandlerFactory {
private static HTTPClientBuilderServiceImpl instance = new HTTPClientBuilderServiceImpl();
private CAppMgtHandlerFactory(){}
/**
* Returns an HTTPS client for communicating with the MI server with basic auth.
*
* @param serverUrl HTTPS URL of the MI server.
* @param username Username.
* @param password Password.
* @return ErrorHandlerServiceStub instance which functions as the HTTPS client.
*/
public static CAppMgtServiceStub getCAppMgtHttpsClient(String serverUrl, String username,
String password) {
return instance.buildWithBasicAuth(username, password, | // Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/CAppMgtServiceStub.java
// public interface CAppMgtServiceStub {
//
// @RequestLine("GET /management/login")
// @Headers("accept: application/json; charset=utf-8")
// Response doAuthenticate() throws CAppMgtServiceStubException;
//
// @RequestLine("POST /management/applications")
// @Headers("Content-Type: multipart/form-data; charset=utf-8")
// Response deployCApp(@Param("file") File capp) throws CAppMgtServiceStubException;
//
// @RequestLine("DELETE /management/applications/{name}")
// @Headers("Content-Type: application/json; charset=utf-8")
// Response unDeployCApp(@Param("name") String cAppName) throws CAppMgtServiceStubException;
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/impl/HTTPClientBuilderServiceImpl.java
// public class HTTPClientBuilderServiceImpl implements HTTPClientBuilderService {
//
// public Client newDefaultClientInstance() {
// return new Client.Default(null, null);
// }
//
// @Override
// public <T> T buildWithBasicAuth(String username, String password, int connectTimeoutMillis, int readTimeoutMillis,
// Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new BasicAuthRequestInterceptor(username, password))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWTAndFormEncoder(String accessToken, int connectTimeoutMillis,
// int readTimeoutMillis, Class<T> target, String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new FormEncoder())
// .decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// @Override
// public <T> T buildWithJWT(String accessToken, int connectTimeoutMillis, int readTimeoutMillis, Class<T> target,
// String url) {
// return Feign.builder().requestInterceptor(new JWTAuthRequestInterceptor(accessToken))
// .encoder(new Encoder.Default()).decoder(new Decoder.Default())
// .options(new Request.Options(connectTimeoutMillis, readTimeoutMillis))
// .client(newDefaultClientInstance())
// .target(target, url);
// }
//
// }
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_CONNECTION_TIMEOUT = 5000;
//
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/Constants.java
// public static final int CLIENT_READ_TIMEOUT = 5000;
// Path: maven-car-deploy-plugin/src/main/java/org/wso2/maven/car/artifact/util/CAppMgtHandlerFactory.java
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_CONNECTION_TIMEOUT;
import static org.wso2.maven.car.artifact.util.Constants.CLIENT_READ_TIMEOUT;
import org.wso2.maven.car.artifact.CAppMgtServiceStub;
import org.wso2.maven.car.artifact.impl.HTTPClientBuilderServiceImpl;
/*
*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.maven.car.artifact.util;
public class CAppMgtHandlerFactory {
private static HTTPClientBuilderServiceImpl instance = new HTTPClientBuilderServiceImpl();
private CAppMgtHandlerFactory(){}
/**
* Returns an HTTPS client for communicating with the MI server with basic auth.
*
* @param serverUrl HTTPS URL of the MI server.
* @param username Username.
* @param password Password.
* @return ErrorHandlerServiceStub instance which functions as the HTTPS client.
*/
public static CAppMgtServiceStub getCAppMgtHttpsClient(String serverUrl, String username,
String password) {
return instance.buildWithBasicAuth(username, password, | CLIENT_CONNECTION_TIMEOUT, CLIENT_READ_TIMEOUT, CAppMgtServiceStub.class, serverUrl); |
wso2/maven-tools | wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/SynapseTestCaseFileReader.java | // Path: wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/Constants.java
// static final String RELATIVE_PREVIOUS = "..";
| import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static org.wso2.synapse.unittest.Constants.RELATIVE_PREVIOUS;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.codehaus.plexus.util.Base64;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files; | //Read mock-services data
processMockServicesData(mockServicesNode);
return importedXMLFile.toString();
} catch (IOException | XMLStreamException e) {
getLog().error("Artifact data reading failed ", e);
}
return null;
}
/**
* Method of processing test-artifact data.
* Reads artifacts from user defined file and append it to the artifact node
*
* @param artifactsNode artifact data contain node
*/
private static void processTestArtifactData(OMElement artifactsNode) throws IOException, XMLStreamException {
//Read artifacts from SynapseTestCase file
QName qualifiedTestArtifact = new QName("", Constants.TEST_ARTIFACT, "");
OMElement testArtifactNode = artifactsNode.getFirstChildWithName(qualifiedTestArtifact);
//Read test-artifact data
QName qualifiedArtifact = new QName("", Constants.ARTIFACT, "");
OMElement testArtifactFileNode = testArtifactNode.getFirstChildWithName(qualifiedArtifact);
String testArtifactFileAsString;
if (!testArtifactFileNode.getText().isEmpty()) {
String testArtifactFilePath = testArtifactFileNode.getText(); | // Path: wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/Constants.java
// static final String RELATIVE_PREVIOUS = "..";
// Path: wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/SynapseTestCaseFileReader.java
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static org.wso2.synapse.unittest.Constants.RELATIVE_PREVIOUS;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.codehaus.plexus.util.Base64;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
//Read mock-services data
processMockServicesData(mockServicesNode);
return importedXMLFile.toString();
} catch (IOException | XMLStreamException e) {
getLog().error("Artifact data reading failed ", e);
}
return null;
}
/**
* Method of processing test-artifact data.
* Reads artifacts from user defined file and append it to the artifact node
*
* @param artifactsNode artifact data contain node
*/
private static void processTestArtifactData(OMElement artifactsNode) throws IOException, XMLStreamException {
//Read artifacts from SynapseTestCase file
QName qualifiedTestArtifact = new QName("", Constants.TEST_ARTIFACT, "");
OMElement testArtifactNode = artifactsNode.getFirstChildWithName(qualifiedTestArtifact);
//Read test-artifact data
QName qualifiedArtifact = new QName("", Constants.ARTIFACT, "");
OMElement testArtifactFileNode = testArtifactNode.getFirstChildWithName(qualifiedArtifact);
String testArtifactFileAsString;
if (!testArtifactFileNode.getText().isEmpty()) {
String testArtifactFilePath = testArtifactFileNode.getText(); | File testArtifactFile = new File(RELATIVE_PREVIOUS + File.separator + testArtifactFilePath); |
wso2/maven-tools | wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/TestCaseSummary.java | // Path: wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/Constants.java
// static final String SKIPPED_KEY = "SKIPPED";
| import static org.wso2.synapse.unittest.Constants.SKIPPED_KEY; | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.synapse.unittest;
/**
* Class responsible for handling the data of unit testing summary.
*/
public class TestCaseSummary {
private String testSuiteName = "Test";
private int testCaseCount = 0 ;
private int passTestCount = 0;
private int failureTestCount = 0;
private String exception; | // Path: wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/Constants.java
// static final String SKIPPED_KEY = "SKIPPED";
// Path: wso2-synapse-unit-test-plugin/src/main/java/org/wso2/synapse/unittest/TestCaseSummary.java
import static org.wso2.synapse.unittest.Constants.SKIPPED_KEY;
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.synapse.unittest;
/**
* Class responsible for handling the data of unit testing summary.
*/
public class TestCaseSummary {
private String testSuiteName = "Test";
private int testCaseCount = 0 ;
private int passTestCount = 0;
private int failureTestCount = 0;
private String exception; | private String deploymentStatus = SKIPPED_KEY; |
wso2/maven-tools | org.wso2.maven.general/src/main/java/org/wso2/maven/registry/GeneralProjectArtifact.java | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
| import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the .artifact.xml file which keeps the metadata of the artifacts included in an ESB project.
* Structure of the file is as follows.
* <p>
* <?xml version="1.0" encoding="UTF-8"?>
* <artifacts>
* <artifact name="testEndpoint2" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </artifact>
* <artifact name="testEndpoint3" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* </artifact>
* </artifacts>
* <p>
* Oct 15, 2020
*/
public class GeneralProjectArtifact extends RegistryInfoProvider {
private List<RegistryArtifact> registryArtifacts = new ArrayList<RegistryArtifact>();
private static final String NAME = "name";
private static final String VERSION = "version";
private static final String TYPE = "type";
private static final String SERVER_ROLE = "serverRole";
private static final String GROUP_ID = "groupId";
private static final String ARTIFACT = "artifact";
private static final String ARTIFACTS = "artifacts";
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ARTIFACT);
for (OMElement omElement : artifactElements) {
RegistryArtifact artifact = new RegistryArtifact();
artifact.setName(getAttribute(omElement, NAME));
artifact.setVersion(getAttribute(omElement, VERSION));
artifact.setType(getAttribute(omElement, TYPE));
artifact.setServerRole(getAttribute(omElement, SERVER_ROLE));
artifact.setGroupId(getAttribute(omElement, GROUP_ID));
List<OMElement> itemElements = getChildElements(omElement, ITEM);
for (OMElement omElement2 : itemElements) { | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/GeneralProjectArtifact.java
import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the .artifact.xml file which keeps the metadata of the artifacts included in an ESB project.
* Structure of the file is as follows.
* <p>
* <?xml version="1.0" encoding="UTF-8"?>
* <artifacts>
* <artifact name="testEndpoint2" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </artifact>
* <artifact name="testEndpoint3" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* </artifact>
* </artifacts>
* <p>
* Oct 15, 2020
*/
public class GeneralProjectArtifact extends RegistryInfoProvider {
private List<RegistryArtifact> registryArtifacts = new ArrayList<RegistryArtifact>();
private static final String NAME = "name";
private static final String VERSION = "version";
private static final String TYPE = "type";
private static final String SERVER_ROLE = "serverRole";
private static final String GROUP_ID = "groupId";
private static final String ARTIFACT = "artifact";
private static final String ARTIFACTS = "artifacts";
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ARTIFACT);
for (OMElement omElement : artifactElements) {
RegistryArtifact artifact = new RegistryArtifact();
artifact.setName(getAttribute(omElement, NAME));
artifact.setVersion(getAttribute(omElement, VERSION));
artifact.setType(getAttribute(omElement, TYPE));
artifact.setServerRole(getAttribute(omElement, SERVER_ROLE));
artifact.setGroupId(getAttribute(omElement, GROUP_ID));
List<OMElement> itemElements = getChildElements(omElement, ITEM);
for (OMElement omElement2 : itemElements) { | RegistryItem item = getRegistryItem(omElement2); |
wso2/maven-tools | org.wso2.maven.general/src/main/java/org/wso2/maven/registry/GeneralProjectArtifact.java | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
| import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the .artifact.xml file which keeps the metadata of the artifacts included in an ESB project.
* Structure of the file is as follows.
* <p>
* <?xml version="1.0" encoding="UTF-8"?>
* <artifacts>
* <artifact name="testEndpoint2" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </artifact>
* <artifact name="testEndpoint3" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* </artifact>
* </artifacts>
* <p>
* Oct 15, 2020
*/
public class GeneralProjectArtifact extends RegistryInfoProvider {
private List<RegistryArtifact> registryArtifacts = new ArrayList<RegistryArtifact>();
private static final String NAME = "name";
private static final String VERSION = "version";
private static final String TYPE = "type";
private static final String SERVER_ROLE = "serverRole";
private static final String GROUP_ID = "groupId";
private static final String ARTIFACT = "artifact";
private static final String ARTIFACTS = "artifacts";
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ARTIFACT);
for (OMElement omElement : artifactElements) {
RegistryArtifact artifact = new RegistryArtifact();
artifact.setName(getAttribute(omElement, NAME));
artifact.setVersion(getAttribute(omElement, VERSION));
artifact.setType(getAttribute(omElement, TYPE));
artifact.setServerRole(getAttribute(omElement, SERVER_ROLE));
artifact.setGroupId(getAttribute(omElement, GROUP_ID));
List<OMElement> itemElements = getChildElements(omElement, ITEM);
for (OMElement omElement2 : itemElements) {
RegistryItem item = getRegistryItem(omElement2);
artifact.addRegistryElement(item);
}
List<OMElement> itemElements1 = getChildElements(omElement, COLLECTION);
for (OMElement omElement2 : itemElements1) { | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/GeneralProjectArtifact.java
import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.registry;
/**
* This class represents the .artifact.xml file which keeps the metadata of the artifacts included in an ESB project.
* Structure of the file is as follows.
* <p>
* <?xml version="1.0" encoding="UTF-8"?>
* <artifacts>
* <artifact name="testEndpoint2" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <item>
* <file>AdminService.wsdl</file>
* <path>/_system/config/repository/wso2con/wsdl</path>
* <mediaType>application/wsdl+xml</mediaType>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </item>
* </artifact>
* <artifact name="testEndpoint3" version="1.0.0" type="synapse/endpoint"
* groupId="com.example.resource" serverRole="EnterpriseServiceBus">
* <collection>
* <directory>emptyFolder_4</directory>
* <path>/_system/governance/custom/emptyFolder_4</path>
* <properties>
* <property key='keyValue1' value='propertyValue1'/>
* <property key='keyValue2' value='propertyValue2'/>
* </properties>
* </collection>
* </artifact>
* </artifacts>
* <p>
* Oct 15, 2020
*/
public class GeneralProjectArtifact extends RegistryInfoProvider {
private List<RegistryArtifact> registryArtifacts = new ArrayList<RegistryArtifact>();
private static final String NAME = "name";
private static final String VERSION = "version";
private static final String TYPE = "type";
private static final String SERVER_ROLE = "serverRole";
private static final String GROUP_ID = "groupId";
private static final String ARTIFACT = "artifact";
private static final String ARTIFACTS = "artifacts";
protected void deserialize(OMElement documentElement) throws Exception {
List<OMElement> artifactElements = getChildElements(documentElement, ARTIFACT);
for (OMElement omElement : artifactElements) {
RegistryArtifact artifact = new RegistryArtifact();
artifact.setName(getAttribute(omElement, NAME));
artifact.setVersion(getAttribute(omElement, VERSION));
artifact.setType(getAttribute(omElement, TYPE));
artifact.setServerRole(getAttribute(omElement, SERVER_ROLE));
artifact.setGroupId(getAttribute(omElement, GROUP_ID));
List<OMElement> itemElements = getChildElements(omElement, ITEM);
for (OMElement omElement2 : itemElements) {
RegistryItem item = getRegistryItem(omElement2);
artifact.addRegistryElement(item);
}
List<OMElement> itemElements1 = getChildElements(omElement, COLLECTION);
for (OMElement omElement2 : itemElements1) { | RegistryCollection item = getRegistryCollection(omElement2); |
wso2/maven-tools | org.wso2.maven.general/src/main/java/org/wso2/maven/registry/GeneralProjectArtifact.java | // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
| import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | public List<RegistryArtifact> getAllESBArtifacts() {
return Collections.unmodifiableList(registryArtifacts);
}
public OMElement getDocumentElement() {
OMElement documentElement = getElement(ARTIFACTS, EMPTY_STRING);
for (RegistryArtifact esbArtifact : registryArtifacts) {
OMElement artifactElement = getElement(ARTIFACT, EMPTY_STRING);
if (!esbArtifact.isAnonymous()) {
addAttribute(artifactElement, NAME, esbArtifact.getName());
}
if (!esbArtifact.isAnonymous() && esbArtifact.getGroupId() != null) {
addAttribute(artifactElement, GROUP_ID, esbArtifact.getGroupId());
}
if (!esbArtifact.isAnonymous() && esbArtifact.getVersion() != null) {
addAttribute(artifactElement, VERSION, esbArtifact.getVersion());
}
if (esbArtifact.getType() != null) {
addAttribute(artifactElement, TYPE, esbArtifact.getType());
}
if (esbArtifact.getServerRole() != null) {
addAttribute(artifactElement, SERVER_ROLE, esbArtifact.getServerRole());
}
| // Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryCollection.java
// public class RegistryCollection extends RegistryElement {
//
// private String directory;
//
// public String getDirectory() {
// return directory;
// }
//
// public void setDirectory(String directory) {
// this.directory = directory;
// }
//
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryElement.java
// public abstract class RegistryElement {
//
// private String path;
//
// private List<RegistryProperty> properties = new ArrayList<RegistryProperty>();
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getPath() {
// return path;
// }
//
// public List<RegistryProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void addProperty(RegistryProperty property) {
// this.properties.add(property);
// }
//
// public void removeProperty(RegistryProperty property) {
// this.properties.remove(property);
// }
// }
//
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/beans/RegistryItem.java
// public class RegistryItem extends RegistryElement {
//
// private String file;
// private String mediaType;
//
// public void setFile(String file) {
// this.file = file;
// }
//
// public String getFile() {
// return file;
// }
//
// public String getMediaType() {
// return mediaType;
// }
//
// public void setMediaType(String mediaType) {
// this.mediaType = mediaType;
// }
//
// }
// Path: org.wso2.maven.general/src/main/java/org/wso2/maven/registry/GeneralProjectArtifact.java
import org.apache.axiom.om.OMElement;
import org.wso2.maven.registry.beans.RegistryCollection;
import org.wso2.maven.registry.beans.RegistryElement;
import org.wso2.maven.registry.beans.RegistryItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public List<RegistryArtifact> getAllESBArtifacts() {
return Collections.unmodifiableList(registryArtifacts);
}
public OMElement getDocumentElement() {
OMElement documentElement = getElement(ARTIFACTS, EMPTY_STRING);
for (RegistryArtifact esbArtifact : registryArtifacts) {
OMElement artifactElement = getElement(ARTIFACT, EMPTY_STRING);
if (!esbArtifact.isAnonymous()) {
addAttribute(artifactElement, NAME, esbArtifact.getName());
}
if (!esbArtifact.isAnonymous() && esbArtifact.getGroupId() != null) {
addAttribute(artifactElement, GROUP_ID, esbArtifact.getGroupId());
}
if (!esbArtifact.isAnonymous() && esbArtifact.getVersion() != null) {
addAttribute(artifactElement, VERSION, esbArtifact.getVersion());
}
if (esbArtifact.getType() != null) {
addAttribute(artifactElement, TYPE, esbArtifact.getType());
}
if (esbArtifact.getServerRole() != null) {
addAttribute(artifactElement, SERVER_ROLE, esbArtifact.getServerRole());
}
| for (RegistryElement item : esbArtifact.getAllRegistryItems()) { |
wso2/maven-tools | humantask-maven-plugin/src/main/java/org/wso2/maven/humantask/artifact/util/FileManagementUtils.java | // Path: humantask-maven-plugin/src/main/java/org/wso2/maven/humantask/artifact/HumanTaskPluginConstants.java
// public class HumanTaskPluginConstants {
//
// public static final String TARGET_FOLDER_NAME = "target";
//
// public static final String HUMANTASK_DATA_FOLDER_NAME = "ht-tmp";
//
// public static final String ERROR_CREATING_CORRESPONDING_ZIP_FILE = "Error creating corresponding ZIP file";
//
// public static final String HUMANTASK_EXTENSION = ".ht";
//
// public static final String EMPTY_STRING = "";
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.wso2.maven.humantask.artifact.HumanTaskPluginConstants; | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.humantask.artifact.util;
public class FileManagementUtils {
private static final Logger logger = Logger.getLogger(FileManagementUtils.class);
/**
* Creates the humantask archive for the artifact
* @param location
* @param artifactLocation
* @param artifactName
* @return created humantask archive file
* @throws Exception
*/
public static File createArchive(File location, File artifactLocation, String artifactName)
throws Exception {
File targetFolder; | // Path: humantask-maven-plugin/src/main/java/org/wso2/maven/humantask/artifact/HumanTaskPluginConstants.java
// public class HumanTaskPluginConstants {
//
// public static final String TARGET_FOLDER_NAME = "target";
//
// public static final String HUMANTASK_DATA_FOLDER_NAME = "ht-tmp";
//
// public static final String ERROR_CREATING_CORRESPONDING_ZIP_FILE = "Error creating corresponding ZIP file";
//
// public static final String HUMANTASK_EXTENSION = ".ht";
//
// public static final String EMPTY_STRING = "";
// }
// Path: humantask-maven-plugin/src/main/java/org/wso2/maven/humantask/artifact/util/FileManagementUtils.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.wso2.maven.humantask.artifact.HumanTaskPluginConstants;
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.humantask.artifact.util;
public class FileManagementUtils {
private static final Logger logger = Logger.getLogger(FileManagementUtils.class);
/**
* Creates the humantask archive for the artifact
* @param location
* @param artifactLocation
* @param artifactName
* @return created humantask archive file
* @throws Exception
*/
public static File createArchive(File location, File artifactLocation, String artifactName)
throws Exception {
File targetFolder; | targetFolder = new File(location.getPath(), HumanTaskPluginConstants.TARGET_FOLDER_NAME); |
GoogleCloudPlatform/weasis-chcapi-extension | src/main/java/org/weasis/dicom/google/api/ui/OAuth2Browser.java | // Path: src/main/java/org/weasis/dicom/google/explorer/Messages.java
// public class Messages {
// private static final String BUNDLE_NAME = "org.weasis.dicom.google.explorer.messages"; //$NON-NLS-1$
//
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// private Messages() {
// }
//
// public static String getString(String key) {
// try {
// return RESOURCE_BUNDLE.getString(key);
// } catch (MissingResourceException e) {
// return '!' + key + '!';
// }
// }
// }
| import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.util.Preconditions;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.awt.Toolkit;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.awt.datatransfer.StringSelection;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.weasis.dicom.google.explorer.Messages; | showNotification(url);
}
} else {
showNotification(url);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to open browser", e);
showNotification(url);
} catch (InternalError e) {
// A bug in a JRE can cause Desktop.isDesktopSupported() to throw an
// InternalError rather than returning false. The error reads,
// "Can't connect to X11 window server using ':0.0' as the value of the
// DISPLAY variable." The exact error message may vary slightly.
LOGGER.log(Level.WARNING, "Unable to open browser", e);
showNotification(url);
}
}
/**
* Copies authorization URL to clipboard and shows notification dialog.
*
* @param url URL to browse.
*/
private static void showNotification(String url) {
// Copy authorization URL to clipboard
final StringSelection selection = new StringSelection(url);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
// Show notification dialog
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(null, | // Path: src/main/java/org/weasis/dicom/google/explorer/Messages.java
// public class Messages {
// private static final String BUNDLE_NAME = "org.weasis.dicom.google.explorer.messages"; //$NON-NLS-1$
//
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// private Messages() {
// }
//
// public static String getString(String key) {
// try {
// return RESOURCE_BUNDLE.getString(key);
// } catch (MissingResourceException e) {
// return '!' + key + '!';
// }
// }
// }
// Path: src/main/java/org/weasis/dicom/google/api/ui/OAuth2Browser.java
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.util.Preconditions;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.awt.Toolkit;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.awt.datatransfer.StringSelection;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.weasis.dicom.google.explorer.Messages;
showNotification(url);
}
} else {
showNotification(url);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Unable to open browser", e);
showNotification(url);
} catch (InternalError e) {
// A bug in a JRE can cause Desktop.isDesktopSupported() to throw an
// InternalError rather than returning false. The error reads,
// "Can't connect to X11 window server using ':0.0' as the value of the
// DISPLAY variable." The exact error message may vary slightly.
LOGGER.log(Level.WARNING, "Unable to open browser", e);
showNotification(url);
}
}
/**
* Copies authorization URL to clipboard and shows notification dialog.
*
* @param url URL to browse.
*/
private static void showNotification(String url) {
// Copy authorization URL to clipboard
final StringSelection selection = new StringSelection(url);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
// Show notification dialog
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(null, | Messages.getString("GoogleAPIClient.open_browser_message")); |
segator/proxylive | src/main/java/com/github/segator/proxylive/tasks/StreamTaskFactory.java | // Path: src/main/java/com/github/segator/proxylive/config/RemoteTranscoder.java
// public class RemoteTranscoder {
// private String endpoint;
// private String profile;
//
// public static RemoteTranscoder CreateFrom(RemoteTranscoder remoteTranscoder) {
// RemoteTranscoder rt= new RemoteTranscoder();
// rt.setEndpoint(remoteTranscoder.getEndpoint());
// rt.setProfile(remoteTranscoder.getProfile());
// return rt;
// }
// public String getEndpoint() {
// return endpoint;
// }
//
// public void setEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// @Override
// public String toString() {
// return "RemoteTranscoder{" +
// "endpoint='" + endpoint + '\'' +
// ", profile='" + profile + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/entity/Channel.java
// public class Channel {
// private Integer number;
// private String name; //used by EPG matching
// private String id; //used by EPG matching
// private String epgID;
// private String logoURL;
// private File logoFile;
// private List<String> categories;
// private List<ChannelSource> sources;
// private String ffmpegParameters="";
// public Channel(){
//
// }
// public static Channel createFromChannel(Channel source){
// Channel channel = new Channel();
// channel.setId(source.getId());
// channel.setCategories(new ArrayList<>(source.getCategories()));
// channel.setEpgID(source.getEpgID());
// channel.setFfmpegParameters(source.getFfmpegParameters());
// channel.setName(source.getName());
// channel.setLogoFile(source.getLogoFile());
// channel.setNumber(source.getNumber());
// channel.setSources(new ArrayList<>(source.getSources()));
// channel.setLogoURL(source.getLogoURL());
// return channel;
// }
//
//
// public Integer getNumber() {
// return number;
// }
//
// public void setNumber(Integer number) {
// this.number = number;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLogoURL() {
// return logoURL;
// }
//
// public void setLogoURL(String logoURL) {
// this.logoURL = logoURL;
// }
//
// public String getEpgID() {
// return epgID;
// }
//
// public void setEpgID(String epgID) {
// this.epgID = epgID;
// }
//
// public File getLogoFile() {
// return logoFile;
// }
//
// public void setLogoFile(File logoFile) {
// this.logoFile = logoFile;
// }
//
// public List<String> getCategories() {
// return categories;
// }
//
// public void setCategories(List<String> categories) {
// this.categories = categories;
// }
//
// public List<ChannelSource> getSources() {
// return sources;
// }
//
// public ChannelSource getSourceByPriority(int priority){
// Object[] orderedSources = getSources().stream().sorted(new Comparator<ChannelSource>() {
// @Override
// public int compare(ChannelSource o1, ChannelSource o2) {
// return o1.getPriority().compareTo(o2.getPriority());
// }
// }).toArray();
// if(priority> orderedSources.length){
// return null;
// }else {
// return (ChannelSource) orderedSources[priority-1];
// }
//
// }
//
// public void setSources(List<ChannelSource> sources) {
// this.sources = sources;
// }
//
// public String getFfmpegParameters() {
// return ffmpegParameters;
// }
//
// public void setFfmpegParameters(String ffmpegParameters) {
// this.ffmpegParameters = ffmpegParameters;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/processor/IStreamMultiplexerProcessor.java
// public interface IStreamMultiplexerProcessor extends IStreamProcessor {
//
// public ClientBroadcastedInputStream getMultiplexedInputStream();
//
//
// }
| import com.github.segator.proxylive.config.RemoteTranscoder;
import com.github.segator.proxylive.entity.Channel;
import com.github.segator.proxylive.processor.IStreamMultiplexerProcessor;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.tasks;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
@Configuration
public class StreamTaskFactory {
@Bean
@Scope(value = "prototype") | // Path: src/main/java/com/github/segator/proxylive/config/RemoteTranscoder.java
// public class RemoteTranscoder {
// private String endpoint;
// private String profile;
//
// public static RemoteTranscoder CreateFrom(RemoteTranscoder remoteTranscoder) {
// RemoteTranscoder rt= new RemoteTranscoder();
// rt.setEndpoint(remoteTranscoder.getEndpoint());
// rt.setProfile(remoteTranscoder.getProfile());
// return rt;
// }
// public String getEndpoint() {
// return endpoint;
// }
//
// public void setEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// @Override
// public String toString() {
// return "RemoteTranscoder{" +
// "endpoint='" + endpoint + '\'' +
// ", profile='" + profile + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/entity/Channel.java
// public class Channel {
// private Integer number;
// private String name; //used by EPG matching
// private String id; //used by EPG matching
// private String epgID;
// private String logoURL;
// private File logoFile;
// private List<String> categories;
// private List<ChannelSource> sources;
// private String ffmpegParameters="";
// public Channel(){
//
// }
// public static Channel createFromChannel(Channel source){
// Channel channel = new Channel();
// channel.setId(source.getId());
// channel.setCategories(new ArrayList<>(source.getCategories()));
// channel.setEpgID(source.getEpgID());
// channel.setFfmpegParameters(source.getFfmpegParameters());
// channel.setName(source.getName());
// channel.setLogoFile(source.getLogoFile());
// channel.setNumber(source.getNumber());
// channel.setSources(new ArrayList<>(source.getSources()));
// channel.setLogoURL(source.getLogoURL());
// return channel;
// }
//
//
// public Integer getNumber() {
// return number;
// }
//
// public void setNumber(Integer number) {
// this.number = number;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLogoURL() {
// return logoURL;
// }
//
// public void setLogoURL(String logoURL) {
// this.logoURL = logoURL;
// }
//
// public String getEpgID() {
// return epgID;
// }
//
// public void setEpgID(String epgID) {
// this.epgID = epgID;
// }
//
// public File getLogoFile() {
// return logoFile;
// }
//
// public void setLogoFile(File logoFile) {
// this.logoFile = logoFile;
// }
//
// public List<String> getCategories() {
// return categories;
// }
//
// public void setCategories(List<String> categories) {
// this.categories = categories;
// }
//
// public List<ChannelSource> getSources() {
// return sources;
// }
//
// public ChannelSource getSourceByPriority(int priority){
// Object[] orderedSources = getSources().stream().sorted(new Comparator<ChannelSource>() {
// @Override
// public int compare(ChannelSource o1, ChannelSource o2) {
// return o1.getPriority().compareTo(o2.getPriority());
// }
// }).toArray();
// if(priority> orderedSources.length){
// return null;
// }else {
// return (ChannelSource) orderedSources[priority-1];
// }
//
// }
//
// public void setSources(List<ChannelSource> sources) {
// this.sources = sources;
// }
//
// public String getFfmpegParameters() {
// return ffmpegParameters;
// }
//
// public void setFfmpegParameters(String ffmpegParameters) {
// this.ffmpegParameters = ffmpegParameters;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/processor/IStreamMultiplexerProcessor.java
// public interface IStreamMultiplexerProcessor extends IStreamProcessor {
//
// public ClientBroadcastedInputStream getMultiplexedInputStream();
//
//
// }
// Path: src/main/java/com/github/segator/proxylive/tasks/StreamTaskFactory.java
import com.github.segator.proxylive.config.RemoteTranscoder;
import com.github.segator.proxylive.entity.Channel;
import com.github.segator.proxylive.processor.IStreamMultiplexerProcessor;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.tasks;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
@Configuration
public class StreamTaskFactory {
@Bean
@Scope(value = "prototype") | public HttpDownloaderTask HttpDownloaderTask(Channel channel) throws IOException { |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/LDAPAuthenticationService.java | // Path: src/main/java/com/github/segator/proxylive/config/LDAPAutentication.java
// public class LDAPAutentication {
//
// private String server, searchBase, user, password;
//
// public String getServer() {
// return server;
// }
//
// public void setServer(String server) {
// this.server = server;
// }
//
// public String getSearchBase() {
// return searchBase;
// }
//
// public void setSearchBase(String searchBase) {
// this.searchBase = searchBase;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.config.LDAPAutentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class LDAPAuthenticationService implements AuthenticationService {
private final Logger logger = LoggerFactory.getLogger(LDAPAuthenticationService.class); | // Path: src/main/java/com/github/segator/proxylive/config/LDAPAutentication.java
// public class LDAPAutentication {
//
// private String server, searchBase, user, password;
//
// public String getServer() {
// return server;
// }
//
// public void setServer(String server) {
// this.server = server;
// }
//
// public String getSearchBase() {
// return searchBase;
// }
//
// public void setSearchBase(String searchBase) {
// this.searchBase = searchBase;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/LDAPAuthenticationService.java
import com.github.segator.proxylive.config.LDAPAutentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class LDAPAuthenticationService implements AuthenticationService {
private final Logger logger = LoggerFactory.getLogger(LDAPAuthenticationService.class); | private LDAPAutentication ldapAuthConfig; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/LDAPAuthenticationService.java | // Path: src/main/java/com/github/segator/proxylive/config/LDAPAutentication.java
// public class LDAPAutentication {
//
// private String server, searchBase, user, password;
//
// public String getServer() {
// return server;
// }
//
// public void setServer(String server) {
// this.server = server;
// }
//
// public String getSearchBase() {
// return searchBase;
// }
//
// public void setSearchBase(String searchBase) {
// this.searchBase = searchBase;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.config.LDAPAutentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class LDAPAuthenticationService implements AuthenticationService {
private final Logger logger = LoggerFactory.getLogger(LDAPAuthenticationService.class);
private LDAPAutentication ldapAuthConfig; | // Path: src/main/java/com/github/segator/proxylive/config/LDAPAutentication.java
// public class LDAPAutentication {
//
// private String server, searchBase, user, password;
//
// public String getServer() {
// return server;
// }
//
// public void setServer(String server) {
// this.server = server;
// }
//
// public String getSearchBase() {
// return searchBase;
// }
//
// public void setSearchBase(String searchBase) {
// this.searchBase = searchBase;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/LDAPAuthenticationService.java
import com.github.segator.proxylive.config.LDAPAutentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class LDAPAuthenticationService implements AuthenticationService {
private final Logger logger = LoggerFactory.getLogger(LDAPAuthenticationService.class);
private LDAPAutentication ldapAuthConfig; | private final ProxyLiveConfiguration configuration; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/LDAPAuthenticationService.java | // Path: src/main/java/com/github/segator/proxylive/config/LDAPAutentication.java
// public class LDAPAutentication {
//
// private String server, searchBase, user, password;
//
// public String getServer() {
// return server;
// }
//
// public void setServer(String server) {
// this.server = server;
// }
//
// public String getSearchBase() {
// return searchBase;
// }
//
// public void setSearchBase(String searchBase) {
// this.searchBase = searchBase;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.config.LDAPAutentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class LDAPAuthenticationService implements AuthenticationService {
private final Logger logger = LoggerFactory.getLogger(LDAPAuthenticationService.class);
private LDAPAutentication ldapAuthConfig;
private final ProxyLiveConfiguration configuration;
public LDAPAuthenticationService(ProxyLiveConfiguration configuration) {
this.configuration = configuration;
}
@Override
public boolean loginUser(String user, String password) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<GrantedAuthority> getUserRoles(String user) {
ArrayList<GrantedAuthority> roles = new ArrayList(); | // Path: src/main/java/com/github/segator/proxylive/config/LDAPAutentication.java
// public class LDAPAutentication {
//
// private String server, searchBase, user, password;
//
// public String getServer() {
// return server;
// }
//
// public void setServer(String server) {
// this.server = server;
// }
//
// public String getSearchBase() {
// return searchBase;
// }
//
// public void setSearchBase(String searchBase) {
// this.searchBase = searchBase;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/LDAPAuthenticationService.java
import com.github.segator.proxylive.config.LDAPAutentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class LDAPAuthenticationService implements AuthenticationService {
private final Logger logger = LoggerFactory.getLogger(LDAPAuthenticationService.class);
private LDAPAutentication ldapAuthConfig;
private final ProxyLiveConfiguration configuration;
public LDAPAuthenticationService(ProxyLiveConfiguration configuration) {
this.configuration = configuration;
}
@Override
public boolean loginUser(String user, String password) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<GrantedAuthority> getUserRoles(String user) {
ArrayList<GrantedAuthority> roles = new ArrayList(); | roles.add(new SimpleGrantedAuthority(AuthorityRoles.USER.getAuthority())); |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/GeoIPService.java | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
| import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.zip.GZIPInputStream; | package com.github.segator.proxylive.service;
@Service
public class GeoIPService {
private final Logger logger = LoggerFactory.getLogger(GeoIPService.class);
private File tmpGEOIPFile;
private DatabaseReader geoIPDB; | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/GeoIPService.java
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
package com.github.segator.proxylive.service;
@Service
public class GeoIPService {
private final Logger logger = LoggerFactory.getLogger(GeoIPService.class);
private File tmpGEOIPFile;
private DatabaseReader geoIPDB; | private final ProxyLiveConfiguration config; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/TokenService.java | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
| import com.github.segator.proxylive.helper.AuthorityRoles;
import com.github.segator.proxylive.helper.JwtHelper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Calendar;
import java.util.List; | package com.github.segator.proxylive.service;
@Service
public class TokenService { | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/TokenService.java
import com.github.segator.proxylive.helper.AuthorityRoles;
import com.github.segator.proxylive.helper.JwtHelper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Calendar;
import java.util.List;
package com.github.segator.proxylive.service;
@Service
public class TokenService { | private final JwtHelper jwtHelper; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/TokenService.java | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
| import com.github.segator.proxylive.helper.AuthorityRoles;
import com.github.segator.proxylive.helper.JwtHelper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Calendar;
import java.util.List; | package com.github.segator.proxylive.service;
@Service
public class TokenService {
private final JwtHelper jwtHelper;
public TokenService(JwtHelper jwtHelper) {
this.jwtHelper = jwtHelper;
}
public String createServiceAccountRequestToken(String subject){
List<GrantedAuthority> grantedAuthorities = AuthorityUtils
.createAuthorityList( | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/TokenService.java
import com.github.segator.proxylive.helper.AuthorityRoles;
import com.github.segator.proxylive.helper.JwtHelper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Calendar;
import java.util.List;
package com.github.segator.proxylive.service;
@Service
public class TokenService {
private final JwtHelper jwtHelper;
public TokenService(JwtHelper jwtHelper) {
this.jwtHelper = jwtHelper;
}
public String createServiceAccountRequestToken(String subject){
List<GrantedAuthority> grantedAuthorities = AuthorityUtils
.createAuthorityList( | AuthorityRoles.SERVICE_ACCOUNT.getAuthority(), |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/WithoutAuthenticationService.java | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.helper.AuthorityRoles;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.ArrayList;
import java.util.List; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class WithoutAuthenticationService implements AuthenticationService {
@Override
public boolean loginUser(String user, String password) throws Exception {
return true;
}
@Override
public List<GrantedAuthority> getUserRoles(String user) {
ArrayList<GrantedAuthority> roles = new ArrayList();
| // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/WithoutAuthenticationService.java
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class WithoutAuthenticationService implements AuthenticationService {
@Override
public boolean loginUser(String user, String password) throws Exception {
return true;
}
@Override
public List<GrantedAuthority> getUserRoles(String user) {
ArrayList<GrantedAuthority> roles = new ArrayList();
| roles.add(new SimpleGrantedAuthority(AuthorityRoles.USER.getAuthority())); |
segator/proxylive | src/main/java/com/github/segator/proxylive/profiler/FFmpegProfilerService.java | // Path: src/main/java/com/github/segator/proxylive/config/FFMpegProfile.java
// public class FFMpegProfile {
// private String alias;
// private RemoteTranscoder transcoder;
// private String parameters;
// private Integer adaptiveBandWith;
// private String adaptiveResolution;
//
// public Integer getAdaptiveBandWith() {
// return adaptiveBandWith;
// }
//
// public void setAdaptiveBandWith(Integer adaptiveBandWith) {
// this.adaptiveBandWith = adaptiveBandWith;
// }
//
// public String getAdaptiveResolution() {
// return adaptiveResolution;
// }
//
// public void setAdaptiveResolution(String adaptiveResolution) {
// this.adaptiveResolution = adaptiveResolution;
// }
//
// public String getAlias() {
// return alias;
// }
//
// public void setAlias(String alias) {
// this.alias = alias;
// }
//
// public String getParameters() {
// return parameters;
// }
//
// public void setParameters(String parameters) {
// this.parameters = parameters;
// }
//
// public boolean isLocalTranscoding(){
// return transcoder==null;
// }
//
// public RemoteTranscoder getTranscoder() {
// return transcoder;
// }
//
// public void setTranscoder(RemoteTranscoder transcoder) {
// this.transcoder = transcoder;
// }
//
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
| import com.github.segator.proxylive.config.FFMpegProfile;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.nio.file.Paths; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.profiler;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
@Service
public class FFmpegProfilerService {
@Autowired | // Path: src/main/java/com/github/segator/proxylive/config/FFMpegProfile.java
// public class FFMpegProfile {
// private String alias;
// private RemoteTranscoder transcoder;
// private String parameters;
// private Integer adaptiveBandWith;
// private String adaptiveResolution;
//
// public Integer getAdaptiveBandWith() {
// return adaptiveBandWith;
// }
//
// public void setAdaptiveBandWith(Integer adaptiveBandWith) {
// this.adaptiveBandWith = adaptiveBandWith;
// }
//
// public String getAdaptiveResolution() {
// return adaptiveResolution;
// }
//
// public void setAdaptiveResolution(String adaptiveResolution) {
// this.adaptiveResolution = adaptiveResolution;
// }
//
// public String getAlias() {
// return alias;
// }
//
// public void setAlias(String alias) {
// this.alias = alias;
// }
//
// public String getParameters() {
// return parameters;
// }
//
// public void setParameters(String parameters) {
// this.parameters = parameters;
// }
//
// public boolean isLocalTranscoding(){
// return transcoder==null;
// }
//
// public RemoteTranscoder getTranscoder() {
// return transcoder;
// }
//
// public void setTranscoder(RemoteTranscoder transcoder) {
// this.transcoder = transcoder;
// }
//
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/profiler/FFmpegProfilerService.java
import com.github.segator.proxylive.config.FFMpegProfile;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.nio.file.Paths;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.profiler;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
@Service
public class FFmpegProfilerService {
@Autowired | private ProxyLiveConfiguration config; |
segator/proxylive | src/main/java/com/github/segator/proxylive/profiler/FFmpegProfilerService.java | // Path: src/main/java/com/github/segator/proxylive/config/FFMpegProfile.java
// public class FFMpegProfile {
// private String alias;
// private RemoteTranscoder transcoder;
// private String parameters;
// private Integer adaptiveBandWith;
// private String adaptiveResolution;
//
// public Integer getAdaptiveBandWith() {
// return adaptiveBandWith;
// }
//
// public void setAdaptiveBandWith(Integer adaptiveBandWith) {
// this.adaptiveBandWith = adaptiveBandWith;
// }
//
// public String getAdaptiveResolution() {
// return adaptiveResolution;
// }
//
// public void setAdaptiveResolution(String adaptiveResolution) {
// this.adaptiveResolution = adaptiveResolution;
// }
//
// public String getAlias() {
// return alias;
// }
//
// public void setAlias(String alias) {
// this.alias = alias;
// }
//
// public String getParameters() {
// return parameters;
// }
//
// public void setParameters(String parameters) {
// this.parameters = parameters;
// }
//
// public boolean isLocalTranscoding(){
// return transcoder==null;
// }
//
// public RemoteTranscoder getTranscoder() {
// return transcoder;
// }
//
// public void setTranscoder(RemoteTranscoder transcoder) {
// this.transcoder = transcoder;
// }
//
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
| import com.github.segator.proxylive.config.FFMpegProfile;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.nio.file.Paths; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.profiler;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
@Service
public class FFmpegProfilerService {
@Autowired
private ProxyLiveConfiguration config;
| // Path: src/main/java/com/github/segator/proxylive/config/FFMpegProfile.java
// public class FFMpegProfile {
// private String alias;
// private RemoteTranscoder transcoder;
// private String parameters;
// private Integer adaptiveBandWith;
// private String adaptiveResolution;
//
// public Integer getAdaptiveBandWith() {
// return adaptiveBandWith;
// }
//
// public void setAdaptiveBandWith(Integer adaptiveBandWith) {
// this.adaptiveBandWith = adaptiveBandWith;
// }
//
// public String getAdaptiveResolution() {
// return adaptiveResolution;
// }
//
// public void setAdaptiveResolution(String adaptiveResolution) {
// this.adaptiveResolution = adaptiveResolution;
// }
//
// public String getAlias() {
// return alias;
// }
//
// public void setAlias(String alias) {
// this.alias = alias;
// }
//
// public String getParameters() {
// return parameters;
// }
//
// public void setParameters(String parameters) {
// this.parameters = parameters;
// }
//
// public boolean isLocalTranscoding(){
// return transcoder==null;
// }
//
// public RemoteTranscoder getTranscoder() {
// return transcoder;
// }
//
// public void setTranscoder(RemoteTranscoder transcoder) {
// this.transcoder = transcoder;
// }
//
//
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/profiler/FFmpegProfilerService.java
import com.github.segator.proxylive.config.FFMpegProfile;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.nio.file.Paths;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.profiler;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
@Service
public class FFmpegProfilerService {
@Autowired
private ProxyLiveConfiguration config;
| public FFMpegProfile getProfile(String profile) { |
segator/proxylive | src/main/java/com/github/segator/proxylive/entity/ClientInfo.java | // Path: src/main/java/com/github/segator/proxylive/processor/IStreamProcessor.java
// public interface IStreamProcessor {
//
// public void start() throws Exception;
//
// public void stop(boolean force) throws IOException;
//
//
//
// public boolean isConnected();
//
// public IStreamTask getTask();
//
// public String getIdentifier();
//
//
// }
| import com.github.segator.proxylive.processor.IStreamProcessor;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.entity;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public class ClientInfo {
private String clientUser;
private InetAddress ip;
private GEOInfo geoInfo;
private String browserInfo; | // Path: src/main/java/com/github/segator/proxylive/processor/IStreamProcessor.java
// public interface IStreamProcessor {
//
// public void start() throws Exception;
//
// public void stop(boolean force) throws IOException;
//
//
//
// public boolean isConnected();
//
// public IStreamTask getTask();
//
// public String getIdentifier();
//
//
// }
// Path: src/main/java/com/github/segator/proxylive/entity/ClientInfo.java
import com.github.segator.proxylive.processor.IStreamProcessor;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.entity;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public class ClientInfo {
private String clientUser;
private InetAddress ip;
private GEOInfo geoInfo;
private String browserInfo; | private List<IStreamProcessor> streams; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/AuthenticationServiceFactory.java | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
| import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.segator.proxylive.config.ProxyLiveConfiguration; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
@Configuration
public class AuthenticationServiceFactory { | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationServiceFactory.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
@Configuration
public class AuthenticationServiceFactory { | private final ProxyLiveConfiguration config; |
segator/proxylive | src/main/java/com/github/segator/proxylive/processor/IStreamProcessor.java | // Path: src/main/java/com/github/segator/proxylive/tasks/IStreamTask.java
// public interface IStreamTask extends Runnable {
// public String getSource();
//
// public boolean isCrashed();
//
// public void terminate();
//
// public String getIdentifier();
//
// public void initializate() throws Exception;
//
// public IStreamProcessor getSourceProcessor();
//
// public Date startTaskDate();
// }
| import com.github.segator.proxylive.tasks.IStreamTask;
import java.io.IOException; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.processor;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public interface IStreamProcessor {
public void start() throws Exception;
public void stop(boolean force) throws IOException;
public boolean isConnected();
| // Path: src/main/java/com/github/segator/proxylive/tasks/IStreamTask.java
// public interface IStreamTask extends Runnable {
// public String getSource();
//
// public boolean isCrashed();
//
// public void terminate();
//
// public String getIdentifier();
//
// public void initializate() throws Exception;
//
// public IStreamProcessor getSourceProcessor();
//
// public Date startTaskDate();
// }
// Path: src/main/java/com/github/segator/proxylive/processor/IStreamProcessor.java
import com.github.segator.proxylive.tasks.IStreamTask;
import java.io.IOException;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.processor;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public interface IStreamProcessor {
public void start() throws Exception;
public void stop(boolean force) throws IOException;
public boolean isConnected();
| public IStreamTask getTask(); |
segator/proxylive | src/main/java/com/github/segator/proxylive/config/JWTBasicFilter.java | // Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
| import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import io.jsonwebtoken.*;
import org.apache.http.client.utils.URIBuilder;
import org.eclipse.jgit.util.Base64;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | package com.github.segator.proxylive.config;
@Component
public class JWTBasicFilter extends OncePerRequestFilter {
private final String HEADER = "Authorization";
private final String PREFIXBearer = "Bearer ";
private final String PREFIXBasic = "Basic ";
private final String PARAM_OLD_USERNAME="user";
private final String PARAM_OLD_PASSWORD="pass";
private final JwtConfiguration jwtConfiguration; | // Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
// Path: src/main/java/com/github/segator/proxylive/config/JWTBasicFilter.java
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import io.jsonwebtoken.*;
import org.apache.http.client.utils.URIBuilder;
import org.eclipse.jgit.util.Base64;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
package com.github.segator.proxylive.config;
@Component
public class JWTBasicFilter extends OncePerRequestFilter {
private final String HEADER = "Authorization";
private final String PREFIXBearer = "Bearer ";
private final String PREFIXBasic = "Basic ";
private final String PARAM_OLD_USERNAME="user";
private final String PARAM_OLD_PASSWORD="pass";
private final JwtConfiguration jwtConfiguration; | private final AuthenticationService authenticationService; |
segator/proxylive | src/main/java/com/github/segator/proxylive/config/JWTBasicFilter.java | // Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
| import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import io.jsonwebtoken.*;
import org.apache.http.client.utils.URIBuilder;
import org.eclipse.jgit.util.Base64;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | package com.github.segator.proxylive.config;
@Component
public class JWTBasicFilter extends OncePerRequestFilter {
private final String HEADER = "Authorization";
private final String PREFIXBearer = "Bearer ";
private final String PREFIXBasic = "Basic ";
private final String PARAM_OLD_USERNAME="user";
private final String PARAM_OLD_PASSWORD="pass";
private final JwtConfiguration jwtConfiguration;
private final AuthenticationService authenticationService; | // Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
// Path: src/main/java/com/github/segator/proxylive/config/JWTBasicFilter.java
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import io.jsonwebtoken.*;
import org.apache.http.client.utils.URIBuilder;
import org.eclipse.jgit.util.Base64;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
package com.github.segator.proxylive.config;
@Component
public class JWTBasicFilter extends OncePerRequestFilter {
private final String HEADER = "Authorization";
private final String PREFIXBearer = "Bearer ";
private final String PREFIXBasic = "Basic ";
private final String PARAM_OLD_USERNAME="user";
private final String PARAM_OLD_PASSWORD="pass";
private final JwtConfiguration jwtConfiguration;
private final AuthenticationService authenticationService; | private final JwtHelper jwtHelper; |
segator/proxylive | src/main/java/com/github/segator/proxylive/stream/UDPInputStream.java | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/EPGService.java
// @Service
// public class EPGService {
// private final Logger logger = LoggerFactory.getLogger(EPGService.class);
// private File tempEPGFile;
//
// private final ProxyLiveConfiguration config;
// private long lastUpdate=0;
//
// public EPGService(ProxyLiveConfiguration config) {
// this.config = config;
// }
//
// @Scheduled(fixedDelay = 600 * 1000) //Every 100 Minute
// @PostConstruct
// private void buildEPG() throws Exception {
// if(config.getSource().getEpg()==null || config.getSource().getEpg().getUrl()==null ){
// return;
// }
// if(new Date().getTime()-lastUpdate>+(config.getSource().getEpg().getRefresh()*1000)) {
// logger.info("Refreshing EPG");
// HttpURLConnection connection = getURLConnection(config.getSource().getEpg().getUrl());
// if (connection.getResponseCode() != 200) {
// return;
// }
// InputStream channel = connection.getInputStream();
// if(config.getSource().getEpg().getUrl().endsWith("gz")){
// channel = new GZIPInputStream(channel);
// }
//
// File tempEPGFileRound = File.createTempFile("epg", "xml");
// FileOutputStream fos = new FileOutputStream(tempEPGFileRound);
// IOUtils.copy(channel, fos);
// fos.flush();
// channel.close();
// fos.close();
// connection.disconnect();
//
// if (tempEPGFile != null && tempEPGFile.exists()) {
// tempEPGFile.delete();
// }
// tempEPGFile = tempEPGFileRound;
// lastUpdate=new Date().getTime();
// }
// }
//
//
// public File getEPG() throws IOException {
// return tempEPGFile;
// }
//
// private HttpURLConnection getURLConnection(String url) throws MalformedURLException, IOException {
// URL tvheadendURL = new URL(url);
// HttpURLConnection connection = (HttpURLConnection) tvheadendURL.openConnection();
// connection.setReadTimeout(10000);
// if (tvheadendURL.getUserInfo() != null) {
// String basicAuth = "Basic " + new String(Base64.getEncoder().encode(tvheadendURL.getUserInfo().getBytes()));
// connection.setRequestProperty("Authorization", basicAuth);
// }
// connection.setRequestMethod("GET");
// connection.connect();
// return connection;
// }
//
// public List<EPGProgram> getEPGFromChannelID(String epgID) {
// List<EPGProgram> epgPrograms = new ArrayList<>();
// return epgPrograms;
// }
// }
| import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.service.EPGService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.regex.Pattern; | package com.github.segator.proxylive.stream;
public class UDPInputStream extends VideoInputStream {
private final Logger logger = LoggerFactory.getLogger(UDPInputStream.class);
private final InetAddress server;
private final int port;
private final byte[] buffer;
private byte[] currentPacket;
private int currentPacketSize;
private int currentPacketPosition=0; | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/EPGService.java
// @Service
// public class EPGService {
// private final Logger logger = LoggerFactory.getLogger(EPGService.class);
// private File tempEPGFile;
//
// private final ProxyLiveConfiguration config;
// private long lastUpdate=0;
//
// public EPGService(ProxyLiveConfiguration config) {
// this.config = config;
// }
//
// @Scheduled(fixedDelay = 600 * 1000) //Every 100 Minute
// @PostConstruct
// private void buildEPG() throws Exception {
// if(config.getSource().getEpg()==null || config.getSource().getEpg().getUrl()==null ){
// return;
// }
// if(new Date().getTime()-lastUpdate>+(config.getSource().getEpg().getRefresh()*1000)) {
// logger.info("Refreshing EPG");
// HttpURLConnection connection = getURLConnection(config.getSource().getEpg().getUrl());
// if (connection.getResponseCode() != 200) {
// return;
// }
// InputStream channel = connection.getInputStream();
// if(config.getSource().getEpg().getUrl().endsWith("gz")){
// channel = new GZIPInputStream(channel);
// }
//
// File tempEPGFileRound = File.createTempFile("epg", "xml");
// FileOutputStream fos = new FileOutputStream(tempEPGFileRound);
// IOUtils.copy(channel, fos);
// fos.flush();
// channel.close();
// fos.close();
// connection.disconnect();
//
// if (tempEPGFile != null && tempEPGFile.exists()) {
// tempEPGFile.delete();
// }
// tempEPGFile = tempEPGFileRound;
// lastUpdate=new Date().getTime();
// }
// }
//
//
// public File getEPG() throws IOException {
// return tempEPGFile;
// }
//
// private HttpURLConnection getURLConnection(String url) throws MalformedURLException, IOException {
// URL tvheadendURL = new URL(url);
// HttpURLConnection connection = (HttpURLConnection) tvheadendURL.openConnection();
// connection.setReadTimeout(10000);
// if (tvheadendURL.getUserInfo() != null) {
// String basicAuth = "Basic " + new String(Base64.getEncoder().encode(tvheadendURL.getUserInfo().getBytes()));
// connection.setRequestProperty("Authorization", basicAuth);
// }
// connection.setRequestMethod("GET");
// connection.connect();
// return connection;
// }
//
// public List<EPGProgram> getEPGFromChannelID(String epgID) {
// List<EPGProgram> epgPrograms = new ArrayList<>();
// return epgPrograms;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/stream/UDPInputStream.java
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.service.EPGService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.regex.Pattern;
package com.github.segator.proxylive.stream;
public class UDPInputStream extends VideoInputStream {
private final Logger logger = LoggerFactory.getLogger(UDPInputStream.class);
private final InetAddress server;
private final int port;
private final byte[] buffer;
private byte[] currentPacket;
private int currentPacketSize;
private int currentPacketPosition=0; | private ProxyLiveConfiguration config; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/PlexAuthenticationService.java | // Path: src/main/java/com/github/segator/proxylive/config/PlexAuthentication.java
// public class PlexAuthentication {
//
// private String adminUser, adminPass, serverName;
// private long refresh=10800;
//
// public String getAdminUser() {
// return adminUser;
// }
//
// public void setAdminUser(String adminUser) {
// this.adminUser = adminUser;
// }
//
// public String getAdminPass() {
// return adminPass;
// }
//
// public void setAdminPass(String adminPass) {
// this.adminPass = adminPass;
// }
//
// public String getServerName() {
// return serverName;
// }
//
// public void setServerName(String serverName) {
// this.serverName = serverName;
// }
//
// public long getRefresh() {
// return refresh;
// }
//
// public void setRefresh(long refresh) {
// this.refresh = refresh;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.config.PlexAuthentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class PlexAuthenticationService implements AuthenticationService {
Logger logger = LoggerFactory.getLogger(PlexAuthenticationService.class);
private long lastUpdate=0;
private List<String> allowedUsers; | // Path: src/main/java/com/github/segator/proxylive/config/PlexAuthentication.java
// public class PlexAuthentication {
//
// private String adminUser, adminPass, serverName;
// private long refresh=10800;
//
// public String getAdminUser() {
// return adminUser;
// }
//
// public void setAdminUser(String adminUser) {
// this.adminUser = adminUser;
// }
//
// public String getAdminPass() {
// return adminPass;
// }
//
// public void setAdminPass(String adminPass) {
// this.adminPass = adminPass;
// }
//
// public String getServerName() {
// return serverName;
// }
//
// public void setServerName(String serverName) {
// this.serverName = serverName;
// }
//
// public long getRefresh() {
// return refresh;
// }
//
// public void setRefresh(long refresh) {
// this.refresh = refresh;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/PlexAuthenticationService.java
import com.github.segator.proxylive.config.PlexAuthentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class PlexAuthenticationService implements AuthenticationService {
Logger logger = LoggerFactory.getLogger(PlexAuthenticationService.class);
private long lastUpdate=0;
private List<String> allowedUsers; | private final ProxyLiveConfiguration configuration; |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/PlexAuthenticationService.java | // Path: src/main/java/com/github/segator/proxylive/config/PlexAuthentication.java
// public class PlexAuthentication {
//
// private String adminUser, adminPass, serverName;
// private long refresh=10800;
//
// public String getAdminUser() {
// return adminUser;
// }
//
// public void setAdminUser(String adminUser) {
// this.adminUser = adminUser;
// }
//
// public String getAdminPass() {
// return adminPass;
// }
//
// public void setAdminPass(String adminPass) {
// this.adminPass = adminPass;
// }
//
// public String getServerName() {
// return serverName;
// }
//
// public void setServerName(String serverName) {
// this.serverName = serverName;
// }
//
// public long getRefresh() {
// return refresh;
// }
//
// public void setRefresh(long refresh) {
// this.refresh = refresh;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.config.PlexAuthentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class PlexAuthenticationService implements AuthenticationService {
Logger logger = LoggerFactory.getLogger(PlexAuthenticationService.class);
private long lastUpdate=0;
private List<String> allowedUsers;
private final ProxyLiveConfiguration configuration;
public PlexAuthenticationService(ProxyLiveConfiguration configuration) {
this.configuration = configuration;
}
@Override
public boolean loginUser(String user, String password) throws IOException, ParseException {
if(user!=null && allowedUsers.contains(user.toLowerCase())){
//Check user pass is valid
return getUserData(user, password)!=null;
}
return false;
}
@Scheduled(fixedDelay = 30 * 1000)//Every 30 seconds
public void refreshPlexUsers() throws IOException { | // Path: src/main/java/com/github/segator/proxylive/config/PlexAuthentication.java
// public class PlexAuthentication {
//
// private String adminUser, adminPass, serverName;
// private long refresh=10800;
//
// public String getAdminUser() {
// return adminUser;
// }
//
// public void setAdminUser(String adminUser) {
// this.adminUser = adminUser;
// }
//
// public String getAdminPass() {
// return adminPass;
// }
//
// public void setAdminPass(String adminPass) {
// this.adminPass = adminPass;
// }
//
// public String getServerName() {
// return serverName;
// }
//
// public void setServerName(String serverName) {
// this.serverName = serverName;
// }
//
// public long getRefresh() {
// return refresh;
// }
//
// public void setRefresh(long refresh) {
// this.refresh = refresh;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/PlexAuthenticationService.java
import com.github.segator.proxylive.config.PlexAuthentication;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.segator.proxylive.service;
/**
*
* @author isaac
*/
public class PlexAuthenticationService implements AuthenticationService {
Logger logger = LoggerFactory.getLogger(PlexAuthenticationService.class);
private long lastUpdate=0;
private List<String> allowedUsers;
private final ProxyLiveConfiguration configuration;
public PlexAuthenticationService(ProxyLiveConfiguration configuration) {
this.configuration = configuration;
}
@Override
public boolean loginUser(String user, String password) throws IOException, ParseException {
if(user!=null && allowedUsers.contains(user.toLowerCase())){
//Check user pass is valid
return getUserData(user, password)!=null;
}
return false;
}
@Scheduled(fixedDelay = 30 * 1000)//Every 30 seconds
public void refreshPlexUsers() throws IOException { | PlexAuthentication plexAuthConfig = configuration.getAuthentication().getPlex(); |
segator/proxylive | src/main/java/com/github/segator/proxylive/controller/AuthController.java | // Path: src/main/java/com/github/segator/proxylive/entity/LoginResult.java
// @Data
// @RequiredArgsConstructor
// public class LoginResult {
// @NonNull
// private String username;
// @NonNull
// private String jwt;
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
| import com.github.segator.proxylive.entity.LoginResult;
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; | package com.github.segator.proxylive.controller;
@RestController
public class AuthController {
| // Path: src/main/java/com/github/segator/proxylive/entity/LoginResult.java
// @Data
// @RequiredArgsConstructor
// public class LoginResult {
// @NonNull
// private String username;
// @NonNull
// private String jwt;
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
// Path: src/main/java/com/github/segator/proxylive/controller/AuthController.java
import com.github.segator.proxylive.entity.LoginResult;
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
package com.github.segator.proxylive.controller;
@RestController
public class AuthController {
| private final JwtHelper jwtHelper; |
segator/proxylive | src/main/java/com/github/segator/proxylive/controller/AuthController.java | // Path: src/main/java/com/github/segator/proxylive/entity/LoginResult.java
// @Data
// @RequiredArgsConstructor
// public class LoginResult {
// @NonNull
// private String username;
// @NonNull
// private String jwt;
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
| import com.github.segator.proxylive.entity.LoginResult;
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; | package com.github.segator.proxylive.controller;
@RestController
public class AuthController {
private final JwtHelper jwtHelper; | // Path: src/main/java/com/github/segator/proxylive/entity/LoginResult.java
// @Data
// @RequiredArgsConstructor
// public class LoginResult {
// @NonNull
// private String username;
// @NonNull
// private String jwt;
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
// Path: src/main/java/com/github/segator/proxylive/controller/AuthController.java
import com.github.segator.proxylive.entity.LoginResult;
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
package com.github.segator.proxylive.controller;
@RestController
public class AuthController {
private final JwtHelper jwtHelper; | private final AuthenticationService authenticationService; |
segator/proxylive | src/main/java/com/github/segator/proxylive/controller/AuthController.java | // Path: src/main/java/com/github/segator/proxylive/entity/LoginResult.java
// @Data
// @RequiredArgsConstructor
// public class LoginResult {
// @NonNull
// private String username;
// @NonNull
// private String jwt;
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
| import com.github.segator.proxylive.entity.LoginResult;
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; | package com.github.segator.proxylive.controller;
@RestController
public class AuthController {
private final JwtHelper jwtHelper;
private final AuthenticationService authenticationService;
public AuthController(JwtHelper jwtHelper, AuthenticationService authenticationService) {
this.jwtHelper = jwtHelper;
this.authenticationService = authenticationService;
}
@PostMapping(path = "/login", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE }) | // Path: src/main/java/com/github/segator/proxylive/entity/LoginResult.java
// @Data
// @RequiredArgsConstructor
// public class LoginResult {
// @NonNull
// private String username;
// @NonNull
// private String jwt;
// }
//
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
// @Component
// public class JwtHelper {
// private JwtConfiguration jwtConfiguration;
//
// public JwtHelper(JwtConfiguration jwtConfiguration) {
// this.jwtConfiguration = jwtConfiguration;
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(Instant.now().toEpochMilli());
// calendar.add(Calendar.HOUR, jwtConfiguration.getExpireInHours());
// return createJwtForClaims(subject,grantedAuthorities,calendar.getTime());
// }
// public String createJwtForClaims(String subject, List<GrantedAuthority> grantedAuthorities,Date expirationDate) {
// JwtBuilder builder = Jwts.builder().setId("proxylive")
// .setSubject(subject)
// .claim("authorities",grantedAuthorities.stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.toList()))
// .setIssuedAt(new Date(System.currentTimeMillis()));
//
// if(expirationDate!=null) {
// builder.setExpiration(expirationDate);
// }
// return builder.signWith(SignatureAlgorithm.HS512,
// jwtConfiguration.getSecret().getBytes()).compact();
// }
// }
//
// Path: src/main/java/com/github/segator/proxylive/service/AuthenticationService.java
// public interface AuthenticationService {
// public boolean loginUser(String user, String password) throws Exception;
// public List<GrantedAuthority> getUserRoles(String user);
// }
// Path: src/main/java/com/github/segator/proxylive/controller/AuthController.java
import com.github.segator.proxylive.entity.LoginResult;
import com.github.segator.proxylive.helper.JwtHelper;
import com.github.segator.proxylive.service.AuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
package com.github.segator.proxylive.controller;
@RestController
public class AuthController {
private final JwtHelper jwtHelper;
private final AuthenticationService authenticationService;
public AuthController(JwtHelper jwtHelper, AuthenticationService authenticationService) {
this.jwtHelper = jwtHelper;
this.authenticationService = authenticationService;
}
@PostMapping(path = "/login", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE }) | public LoginResult login( |
segator/proxylive | src/main/java/com/github/segator/proxylive/config/WebSecurityConfiguration.java | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
| import com.github.segator.proxylive.helper.AuthorityRoles;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component; | package com.github.segator.proxylive.config;
@Component
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final JWTBasicFilter jwtBasicFilter;
private final JwtConfiguration jwtConfiguration;
public WebSecurityConfiguration(JWTBasicFilter jwtBasicFilter, JwtConfiguration jwtConfiguration) {
this.jwtBasicFilter = jwtBasicFilter;
this.jwtConfiguration = jwtConfiguration;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/login","/error","/actuator/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests(configurer ->
configurer
.antMatchers("/channel/**","/view/raw","/api/**") | // Path: src/main/java/com/github/segator/proxylive/helper/AuthorityRoles.java
// public enum AuthorityRoles {
// USER("USER"),
// SERVICE_ACCOUNT("SERVICE_ACCOUNT"),
// ALLOW_ENCODING("ENCODE_PULLER"),
// ADMIN("ADMIN");
// private String authority;
// AuthorityRoles(String authority) {
// this.authority = authority;
// }
//
// public String getAuthority() {
// return authority;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/config/WebSecurityConfiguration.java
import com.github.segator.proxylive.helper.AuthorityRoles;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
package com.github.segator.proxylive.config;
@Component
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final JWTBasicFilter jwtBasicFilter;
private final JwtConfiguration jwtConfiguration;
public WebSecurityConfiguration(JWTBasicFilter jwtBasicFilter, JwtConfiguration jwtConfiguration) {
this.jwtBasicFilter = jwtBasicFilter;
this.jwtConfiguration = jwtConfiguration;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/login","/error","/actuator/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests(configurer ->
configurer
.antMatchers("/channel/**","/view/raw","/api/**") | .hasRole(AuthorityRoles.USER.getAuthority()) |
segator/proxylive | src/main/java/com/github/segator/proxylive/service/ChannelServiceFactory.java | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
| import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; | package com.github.segator.proxylive.service;
@Configuration
public class ChannelServiceFactory {
| // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/service/ChannelServiceFactory.java
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
package com.github.segator.proxylive.service;
@Configuration
public class ChannelServiceFactory {
| private final ProxyLiveConfiguration config; |
segator/proxylive | src/main/java/com/github/segator/proxylive/tasks/IStreamTask.java | // Path: src/main/java/com/github/segator/proxylive/processor/IStreamProcessor.java
// public interface IStreamProcessor {
//
// public void start() throws Exception;
//
// public void stop(boolean force) throws IOException;
//
//
//
// public boolean isConnected();
//
// public IStreamTask getTask();
//
// public String getIdentifier();
//
//
// }
| import com.github.segator.proxylive.processor.IStreamProcessor;
import java.util.Date; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.tasks;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public interface IStreamTask extends Runnable {
public String getSource();
public boolean isCrashed();
public void terminate();
public String getIdentifier();
public void initializate() throws Exception;
| // Path: src/main/java/com/github/segator/proxylive/processor/IStreamProcessor.java
// public interface IStreamProcessor {
//
// public void start() throws Exception;
//
// public void stop(boolean force) throws IOException;
//
//
//
// public boolean isConnected();
//
// public IStreamTask getTask();
//
// public String getIdentifier();
//
//
// }
// Path: src/main/java/com/github/segator/proxylive/tasks/IStreamTask.java
import com.github.segator.proxylive.processor.IStreamProcessor;
import java.util.Date;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.tasks;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public interface IStreamTask extends Runnable {
public String getSource();
public boolean isCrashed();
public void terminate();
public String getIdentifier();
public void initializate() throws Exception;
| public IStreamProcessor getSourceProcessor(); |
segator/proxylive | src/main/java/com/github/segator/proxylive/helper/JwtHelper.java | // Path: src/main/java/com/github/segator/proxylive/config/JwtConfiguration.java
// @Configuration
// public class JwtConfiguration {
// private final Logger logger = LoggerFactory.getLogger(JwtConfiguration.class);
// private String secret;
// private Integer expireInHours;
//
// JwtConfiguration( @Value("${authentication.secret:}")String secret,@Value("${authentication.expireInHours}")Integer expireInHours){
// if(secret.isEmpty()){
// this.secret = RandomStringUtils.randomAlphanumeric(65);
// }else{
// this.secret=secret;
// }
// this.expireInHours=expireInHours;
// }
//
//
// public String getSecret() {
// return secret;
// }
//
// public Integer getExpireInHours() {
// return expireInHours;
// }
// }
| import com.github.segator.proxylive.config.JwtConfiguration;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | package com.github.segator.proxylive.helper;
@Component
public class JwtHelper { | // Path: src/main/java/com/github/segator/proxylive/config/JwtConfiguration.java
// @Configuration
// public class JwtConfiguration {
// private final Logger logger = LoggerFactory.getLogger(JwtConfiguration.class);
// private String secret;
// private Integer expireInHours;
//
// JwtConfiguration( @Value("${authentication.secret:}")String secret,@Value("${authentication.expireInHours}")Integer expireInHours){
// if(secret.isEmpty()){
// this.secret = RandomStringUtils.randomAlphanumeric(65);
// }else{
// this.secret=secret;
// }
// this.expireInHours=expireInHours;
// }
//
//
// public String getSecret() {
// return secret;
// }
//
// public Integer getExpireInHours() {
// return expireInHours;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/helper/JwtHelper.java
import com.github.segator.proxylive.config.JwtConfiguration;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
package com.github.segator.proxylive.helper;
@Component
public class JwtHelper { | private JwtConfiguration jwtConfiguration; |
segator/proxylive | src/main/java/com/github/segator/proxylive/stream/WebInputStream.java | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection; | /*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.stream;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public class WebInputStream extends VideoInputStream{
private final Logger logger = LoggerFactory.getLogger(WebInputStream.class);
private final URL url;
private HttpURLConnection connection;
private InputStream httpInputStream; | // Path: src/main/java/com/github/segator/proxylive/config/ProxyLiveConfiguration.java
// @Configuration
// @ConfigurationProperties
// public class ProxyLiveConfiguration {
// private final Logger logger = LoggerFactory.getLogger(DirectTranscodeTask.class);
// private final JwtHelper jwtHelper;
// private BufferingConfiguration buffers;
// private FFMpegConfiguration ffmpeg;
// private HttpLiveSource source;
// private GEOIPDatasource geoIP;
// private AuthenticationConfiguration authentication;
// private String userAgent;
// private int streamTimeout;
//
// public ProxyLiveConfiguration(JwtHelper jwtHelper) {
// this.jwtHelper = jwtHelper;
// }
//
// @PostConstruct
// public void initializeBean() {
//
// //If tvheadend input is set complete configuration
// if(source.getTvheadendURL()!=null){
// if( source.getEpg().getUrl()==null) {
// source.getEpg().setUrl(source.getTvheadendURL() + "/xmltv/channels");
// }
// if(source.getChannels().getUrl()==null) {
// source.getChannels().setUrl(source.getTvheadendURL());
// }
// }
//
//
// }
//
// public FFMpegConfiguration getFfmpeg() {
// return ffmpeg;
// }
//
// public void setFfmpeg(FFMpegConfiguration ffmpeg) {
// this.ffmpeg = ffmpeg;
// }
//
// public HttpLiveSource getSource() {
// return source;
// }
//
// public GEOIPDatasource getGeoIP() {
// return geoIP;
// }
//
// public void setGeoIP(GEOIPDatasource geoIP) {
// this.geoIP = geoIP;
// }
//
// public void setSource(HttpLiveSource source) {
// this.source = source;
// }
//
// public BufferingConfiguration getBuffers() {
// return buffers;
// }
//
// public void setBuffers(BufferingConfiguration buffers) {
// this.buffers = buffers;
// }
//
// public AuthenticationConfiguration getAuthentication() {
// return authentication;
// }
//
// public void setAuthentication(AuthenticationConfiguration authentication) {
// this.authentication = authentication;
// }
//
// public int getStreamTimeout() {
// return streamTimeout;
// }
// public int getStreamTimeoutMilis() {
// return streamTimeout*1000;
// }
//
// public void setStreamTimeout(int streamTimeout) {
// this.streamTimeout = streamTimeout;
// }
//
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
// }
// Path: src/main/java/com/github/segator/proxylive/stream/WebInputStream.java
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import com.github.segator.proxylive.config.ProxyLiveConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
/*
* The MIT License
*
* Copyright 2017 Isaac Aymerich <isaac.aymerich@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.segator.proxylive.stream;
/**
*
* @author Isaac Aymerich <isaac.aymerich@gmail.com>
*/
public class WebInputStream extends VideoInputStream{
private final Logger logger = LoggerFactory.getLogger(WebInputStream.class);
private final URL url;
private HttpURLConnection connection;
private InputStream httpInputStream; | private ProxyLiveConfiguration config; |
envyfan/AndroidReview | app/src/main/java/com/vv/androidreview/ui/activites/PermissionsActivity.java | // Path: app/src/main/java/com/vv/androidreview/utils/PermissionsChecker.java
// public class PermissionsChecker {
// private final Context mContext;
//
// public PermissionsChecker(Context context) {
// mContext = context.getApplicationContext();
// }
//
// // 判断权限集合
// public boolean lacksPermissions(String... permissions) {
// for (String permission : permissions) {
// if (lacksPermission(permission)) {
// return true;
// }
// }
// return false;
// }
//
// // 判断是否缺少权限
// private boolean lacksPermission(String permission) {
// return ContextCompat.checkSelfPermission(mContext, permission) ==
// PackageManager.PERMISSION_DENIED;
// }
// }
| import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.vv.androidreview.R;
import com.vv.androidreview.utils.PermissionsChecker;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog; | /*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.ui.activites;
/**
* 权限获取页面
* <p/>
* Created by wangchenlong on 16/1/26.
*/
public class PermissionsActivity extends AppCompatActivity {
public static final int PERMISSIONS_GRANTED = 0; // 权限授权
public static final int PERMISSIONS_DENIED = 1; // 权限拒绝
private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限管理页面的参数
private static final String EXTRA_PERMISSIONS = "extra_permission"; // 权限参数
private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
| // Path: app/src/main/java/com/vv/androidreview/utils/PermissionsChecker.java
// public class PermissionsChecker {
// private final Context mContext;
//
// public PermissionsChecker(Context context) {
// mContext = context.getApplicationContext();
// }
//
// // 判断权限集合
// public boolean lacksPermissions(String... permissions) {
// for (String permission : permissions) {
// if (lacksPermission(permission)) {
// return true;
// }
// }
// return false;
// }
//
// // 判断是否缺少权限
// private boolean lacksPermission(String permission) {
// return ContextCompat.checkSelfPermission(mContext, permission) ==
// PackageManager.PERMISSION_DENIED;
// }
// }
// Path: app/src/main/java/com/vv/androidreview/ui/activites/PermissionsActivity.java
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.vv.androidreview.R;
import com.vv.androidreview.utils.PermissionsChecker;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
/*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.ui.activites;
/**
* 权限获取页面
* <p/>
* Created by wangchenlong on 16/1/26.
*/
public class PermissionsActivity extends AppCompatActivity {
public static final int PERMISSIONS_GRANTED = 0; // 权限授权
public static final int PERMISSIONS_DENIED = 1; // 权限拒绝
private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限管理页面的参数
private static final String EXTRA_PERMISSIONS = "extra_permission"; // 权限参数
private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
| private PermissionsChecker mChecker; // 权限检测器 |
envyfan/AndroidReview | app/src/main/java/com/vv/androidreview/utils/TDevice.java | // Path: app/src/main/java/com/vv/androidreview/base/BaseApplication.java
// public class BaseApplication extends Application{
//
// public static Context sContext;
// public static Resources sResource;
//
// private static String PREF_NAME = "creativelocker.pref";
// private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
// private static long lastToastTime;
// //运行系统是否为2.3或以上
// public static boolean isAtLeastGB;
//
// static {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
// isAtLeastGB = true;
// }
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// sContext = getApplicationContext();
// sResource = sContext.getResources();
// }
//
// public static synchronized BaseApplication context() {
// return (BaseApplication) sContext;
// }
//
// public static Resources resources() {
// return sResource;
// }
//
// }
//
// Path: app/src/main/java/com/vv/androidreview/base/system/AppContext.java
// public class AppContext extends BaseApplication {
//
// private static AppContext instance;
//
// private static final String ApplicationID = "这里输入你的Bmob ApplicationID";
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// Bmob.initialize(this, ApplicationID);
// //初始化Log系统
// Logger.init("MyDemo") // default PRETTYLOGGER or use just init()
// .setMethodCount(1) // default 2
// .hideThreadInfo(); // default shown
// //异常捕获收集
// // CrashWoodpecker.fly().to(this);
// }
//
// /**
// * 获得当前app运行的AppContext
// *
// * @return
// */
// public static AppContext getInstance() {
// return instance;
// }
//
//
// }
| import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.vv.androidreview.base.BaseApplication;
import com.vv.androidreview.base.system.AppContext;
import java.io.File;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.List; | /*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.utils;
/**
* Author:Vv on 2015/7/21 14:45
* Mail:envyfan@qq.com
* Description:
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class TDevice {
// 手机网络类型
public static final int NETTYPE_WIFI = 0x01;
public static final int NETTYPE_CMWAP = 0x02;
public static final int NETTYPE_CMNET = 0x03;
public static boolean GTE_HC;
public static boolean GTE_ICS;
public static boolean PRE_HC;
private static Boolean _hasBigScreen = null;
private static Boolean _hasCamera = null;
private static Boolean _isTablet = null;
private static Integer _loadFactor = null;
private static int _pageSize = -1;
public static float displayDensity = 0.0F;
static {
GTE_ICS = Build.VERSION.SDK_INT >= 14;
GTE_HC = Build.VERSION.SDK_INT >= 11;
PRE_HC = Build.VERSION.SDK_INT < 11;
}
public TDevice() {
}
public static float dpToPixel(float dp) {
return dp * (getDisplayMetrics().densityDpi / 160F);
}
public static int getDefaultLoadFactor() {
if (_loadFactor == null) { | // Path: app/src/main/java/com/vv/androidreview/base/BaseApplication.java
// public class BaseApplication extends Application{
//
// public static Context sContext;
// public static Resources sResource;
//
// private static String PREF_NAME = "creativelocker.pref";
// private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
// private static long lastToastTime;
// //运行系统是否为2.3或以上
// public static boolean isAtLeastGB;
//
// static {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
// isAtLeastGB = true;
// }
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// sContext = getApplicationContext();
// sResource = sContext.getResources();
// }
//
// public static synchronized BaseApplication context() {
// return (BaseApplication) sContext;
// }
//
// public static Resources resources() {
// return sResource;
// }
//
// }
//
// Path: app/src/main/java/com/vv/androidreview/base/system/AppContext.java
// public class AppContext extends BaseApplication {
//
// private static AppContext instance;
//
// private static final String ApplicationID = "这里输入你的Bmob ApplicationID";
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// Bmob.initialize(this, ApplicationID);
// //初始化Log系统
// Logger.init("MyDemo") // default PRETTYLOGGER or use just init()
// .setMethodCount(1) // default 2
// .hideThreadInfo(); // default shown
// //异常捕获收集
// // CrashWoodpecker.fly().to(this);
// }
//
// /**
// * 获得当前app运行的AppContext
// *
// * @return
// */
// public static AppContext getInstance() {
// return instance;
// }
//
//
// }
// Path: app/src/main/java/com/vv/androidreview/utils/TDevice.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.vv.androidreview.base.BaseApplication;
import com.vv.androidreview.base.system.AppContext;
import java.io.File;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.List;
/*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.utils;
/**
* Author:Vv on 2015/7/21 14:45
* Mail:envyfan@qq.com
* Description:
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class TDevice {
// 手机网络类型
public static final int NETTYPE_WIFI = 0x01;
public static final int NETTYPE_CMWAP = 0x02;
public static final int NETTYPE_CMNET = 0x03;
public static boolean GTE_HC;
public static boolean GTE_ICS;
public static boolean PRE_HC;
private static Boolean _hasBigScreen = null;
private static Boolean _hasCamera = null;
private static Boolean _isTablet = null;
private static Integer _loadFactor = null;
private static int _pageSize = -1;
public static float displayDensity = 0.0F;
static {
GTE_ICS = Build.VERSION.SDK_INT >= 14;
GTE_HC = Build.VERSION.SDK_INT >= 11;
PRE_HC = Build.VERSION.SDK_INT < 11;
}
public TDevice() {
}
public static float dpToPixel(float dp) {
return dp * (getDisplayMetrics().densityDpi / 160F);
}
public static int getDefaultLoadFactor() {
if (_loadFactor == null) { | Integer integer = Integer.valueOf(0xf & BaseApplication.context() |
envyfan/AndroidReview | app/src/main/java/com/vv/androidreview/utils/TDevice.java | // Path: app/src/main/java/com/vv/androidreview/base/BaseApplication.java
// public class BaseApplication extends Application{
//
// public static Context sContext;
// public static Resources sResource;
//
// private static String PREF_NAME = "creativelocker.pref";
// private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
// private static long lastToastTime;
// //运行系统是否为2.3或以上
// public static boolean isAtLeastGB;
//
// static {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
// isAtLeastGB = true;
// }
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// sContext = getApplicationContext();
// sResource = sContext.getResources();
// }
//
// public static synchronized BaseApplication context() {
// return (BaseApplication) sContext;
// }
//
// public static Resources resources() {
// return sResource;
// }
//
// }
//
// Path: app/src/main/java/com/vv/androidreview/base/system/AppContext.java
// public class AppContext extends BaseApplication {
//
// private static AppContext instance;
//
// private static final String ApplicationID = "这里输入你的Bmob ApplicationID";
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// Bmob.initialize(this, ApplicationID);
// //初始化Log系统
// Logger.init("MyDemo") // default PRETTYLOGGER or use just init()
// .setMethodCount(1) // default 2
// .hideThreadInfo(); // default shown
// //异常捕获收集
// // CrashWoodpecker.fly().to(this);
// }
//
// /**
// * 获得当前app运行的AppContext
// *
// * @return
// */
// public static AppContext getInstance() {
// return instance;
// }
//
//
// }
| import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.vv.androidreview.base.BaseApplication;
import com.vv.androidreview.base.system.AppContext;
import java.io.File;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.List; | if ((attrs.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
return false;
} else {
return true;
}
}
/**
* 调用系统安装了的应用分享
*
* @param context
* @param title
* @param url
*/
public static void showSystemShareOption(Activity context,
final String title, final String url) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "分享:" + title);
intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
context.startActivity(Intent.createChooser(intent, "选择分享"));
}
/**
* 获取当前网络类型
*
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/
public static int getNetworkType() {
int netType = 0; | // Path: app/src/main/java/com/vv/androidreview/base/BaseApplication.java
// public class BaseApplication extends Application{
//
// public static Context sContext;
// public static Resources sResource;
//
// private static String PREF_NAME = "creativelocker.pref";
// private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
// private static long lastToastTime;
// //运行系统是否为2.3或以上
// public static boolean isAtLeastGB;
//
// static {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
// isAtLeastGB = true;
// }
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// sContext = getApplicationContext();
// sResource = sContext.getResources();
// }
//
// public static synchronized BaseApplication context() {
// return (BaseApplication) sContext;
// }
//
// public static Resources resources() {
// return sResource;
// }
//
// }
//
// Path: app/src/main/java/com/vv/androidreview/base/system/AppContext.java
// public class AppContext extends BaseApplication {
//
// private static AppContext instance;
//
// private static final String ApplicationID = "这里输入你的Bmob ApplicationID";
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// Bmob.initialize(this, ApplicationID);
// //初始化Log系统
// Logger.init("MyDemo") // default PRETTYLOGGER or use just init()
// .setMethodCount(1) // default 2
// .hideThreadInfo(); // default shown
// //异常捕获收集
// // CrashWoodpecker.fly().to(this);
// }
//
// /**
// * 获得当前app运行的AppContext
// *
// * @return
// */
// public static AppContext getInstance() {
// return instance;
// }
//
//
// }
// Path: app/src/main/java/com/vv/androidreview/utils/TDevice.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.vv.androidreview.base.BaseApplication;
import com.vv.androidreview.base.system.AppContext;
import java.io.File;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.List;
if ((attrs.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
return false;
} else {
return true;
}
}
/**
* 调用系统安装了的应用分享
*
* @param context
* @param title
* @param url
*/
public static void showSystemShareOption(Activity context,
final String title, final String url) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "分享:" + title);
intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
context.startActivity(Intent.createChooser(intent, "选择分享"));
}
/**
* 获取当前网络类型
*
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/
public static int getNetworkType() {
int netType = 0; | ConnectivityManager connectivityManager = (ConnectivityManager) AppContext |
envyfan/AndroidReview | app/src/main/java/com/vv/androidreview/utils/DoubleClickExitHelper.java | // Path: app/src/main/java/com/vv/androidreview/base/system/AppManager.java
// public class AppManager {
//
// private static Stack<Activity> activityStack;
// private static AppManager instance;
//
// private AppManager() {}
//
// /**
// * 单一实例
// */
// public static AppManager getAppManager() {
// if (instance == null) {
// instance = new AppManager();
// }
// return instance;
// }
//
// /**
// * 添加Activity到堆栈
// */
// public void addActivity(Activity activity) {
// if (activityStack == null) {
// activityStack = new Stack<Activity>();
// }
// activityStack.add(activity);
// }
//
// /**
// * 获取当前Activity(堆栈中最后一个压入的)
// */
// public Activity currentActivity() {
// Activity activity = activityStack.lastElement();
// return activity;
// }
//
// /**
// * 结束当前Activity(堆栈中最后一个压入的)
// */
// public void finishActivity() {
// Activity activity = activityStack.lastElement();
// finishActivity(activity);
// }
//
// /**
// * 结束指定的Activity
// */
// public void finishActivity(Activity activity) {
// if (activity != null && !activity.isFinishing()) {
// activityStack.remove(activity);
// activity.finish();
// activity = null;
// }
// }
//
// /**
// * 结束指定类名的Activity
// */
// public void finishActivity(Class<?> cls) {
// for (Activity activity : activityStack) {
// if (activity.getClass().equals(cls)) {
// finishActivity(activity);
// break;
// }
// }
// }
//
// /**
// * 结束所有Activity
// */
// public void finishAllActivity() {
// for (int i = 0, size = activityStack.size(); i < size; i++) {
// if (null != activityStack.get(i)) {
// finishActivity(activityStack.get(i));
// break;
// }
// }
// activityStack.clear();
// }
//
// /**
// * 获取指定的Activity
// *
// * @author kymjs
// */
// public static Activity getActivity(Class<?> cls) {
// if (activityStack != null)
// for (Activity activity : activityStack) {
// if (activity.getClass().equals(cls)) {
// return activity;
// }
// }
// return null;
// }
//
// public static Stack<Activity> getActivitys(){
// return activityStack;
// }
//
// /**
// * 退出应用程序
// */
// public void AppExit(Context context) {
// try {
// finishAllActivity();
// // 杀死该应用进程
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(0);
// } catch (Exception e) {
// }
// }
//
// /**返回当前Activity栈中Activity的数量
// * @return
// */
// public int getActivityCount(){
// int count = activityStack.size();
// return count;
// }
//
// /**
// * 堆栈中移除Activity
// */
// public void removeActivity(Activity activity) {
// if (activityStack == null) {
// return;
// }else if(activityStack.contains(activity)){
// activityStack.remove(activity);
// }
//
// if (activity != null && !activity.isFinishing()) {
// activity.finish();
// activity = null;
// }
// }
// }
| import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;
import com.vv.androidreview.R;
import com.vv.androidreview.base.system.AppManager; | /*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.utils;
/**
* Author:Vv on 2015/7/21 15:30
* Mail:envyfan@qq.com
* Description:双击退出
*/
public class DoubleClickExitHelper {
private final Activity mActivity;
private boolean isOnKeyBacking;
private Handler mHandler;
private Toast mBackToast;
public DoubleClickExitHelper(Activity activity) {
mActivity = activity;
mHandler = new Handler(Looper.getMainLooper());
}
/**
* Activity onKeyDown事件
* */
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode != KeyEvent.KEYCODE_BACK) {
return false;
}
if(isOnKeyBacking) {
mHandler.removeCallbacks(onBackTimeRunnable);
if(mBackToast != null){
mBackToast.cancel();
}
// �?�? | // Path: app/src/main/java/com/vv/androidreview/base/system/AppManager.java
// public class AppManager {
//
// private static Stack<Activity> activityStack;
// private static AppManager instance;
//
// private AppManager() {}
//
// /**
// * 单一实例
// */
// public static AppManager getAppManager() {
// if (instance == null) {
// instance = new AppManager();
// }
// return instance;
// }
//
// /**
// * 添加Activity到堆栈
// */
// public void addActivity(Activity activity) {
// if (activityStack == null) {
// activityStack = new Stack<Activity>();
// }
// activityStack.add(activity);
// }
//
// /**
// * 获取当前Activity(堆栈中最后一个压入的)
// */
// public Activity currentActivity() {
// Activity activity = activityStack.lastElement();
// return activity;
// }
//
// /**
// * 结束当前Activity(堆栈中最后一个压入的)
// */
// public void finishActivity() {
// Activity activity = activityStack.lastElement();
// finishActivity(activity);
// }
//
// /**
// * 结束指定的Activity
// */
// public void finishActivity(Activity activity) {
// if (activity != null && !activity.isFinishing()) {
// activityStack.remove(activity);
// activity.finish();
// activity = null;
// }
// }
//
// /**
// * 结束指定类名的Activity
// */
// public void finishActivity(Class<?> cls) {
// for (Activity activity : activityStack) {
// if (activity.getClass().equals(cls)) {
// finishActivity(activity);
// break;
// }
// }
// }
//
// /**
// * 结束所有Activity
// */
// public void finishAllActivity() {
// for (int i = 0, size = activityStack.size(); i < size; i++) {
// if (null != activityStack.get(i)) {
// finishActivity(activityStack.get(i));
// break;
// }
// }
// activityStack.clear();
// }
//
// /**
// * 获取指定的Activity
// *
// * @author kymjs
// */
// public static Activity getActivity(Class<?> cls) {
// if (activityStack != null)
// for (Activity activity : activityStack) {
// if (activity.getClass().equals(cls)) {
// return activity;
// }
// }
// return null;
// }
//
// public static Stack<Activity> getActivitys(){
// return activityStack;
// }
//
// /**
// * 退出应用程序
// */
// public void AppExit(Context context) {
// try {
// finishAllActivity();
// // 杀死该应用进程
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(0);
// } catch (Exception e) {
// }
// }
//
// /**返回当前Activity栈中Activity的数量
// * @return
// */
// public int getActivityCount(){
// int count = activityStack.size();
// return count;
// }
//
// /**
// * 堆栈中移除Activity
// */
// public void removeActivity(Activity activity) {
// if (activityStack == null) {
// return;
// }else if(activityStack.contains(activity)){
// activityStack.remove(activity);
// }
//
// if (activity != null && !activity.isFinishing()) {
// activity.finish();
// activity = null;
// }
// }
// }
// Path: app/src/main/java/com/vv/androidreview/utils/DoubleClickExitHelper.java
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;
import com.vv.androidreview.R;
import com.vv.androidreview.base.system.AppManager;
/*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.utils;
/**
* Author:Vv on 2015/7/21 15:30
* Mail:envyfan@qq.com
* Description:双击退出
*/
public class DoubleClickExitHelper {
private final Activity mActivity;
private boolean isOnKeyBacking;
private Handler mHandler;
private Toast mBackToast;
public DoubleClickExitHelper(Activity activity) {
mActivity = activity;
mHandler = new Handler(Looper.getMainLooper());
}
/**
* Activity onKeyDown事件
* */
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode != KeyEvent.KEYCODE_BACK) {
return false;
}
if(isOnKeyBacking) {
mHandler.removeCallbacks(onBackTimeRunnable);
if(mBackToast != null){
mBackToast.cancel();
}
// �?�? | AppManager.getAppManager().AppExit(mActivity); |
envyfan/AndroidReview | app/src/main/java/com/vv/androidreview/ui/view/AnswerItem.java | // Path: app/src/main/java/com/vv/androidreview/entity/Test.java
// public class Test extends BmobObject {
//
// private Integer testId;
// private Integer testType;
// private String question;
// private String answer;
// private String answerA;
// private String answerB;
// private String answerC;
// private String answerD;
// private String answerE;
// private String answerF;
// private String answerG;
//
// public String getExplain() {
// return explain;
// }
//
// public void setExplain(String explain) {
// this.explain = explain;
// }
//
// private String explain;
//
//
// public Integer getTestId() {
// return testId;
// }
//
// public void setTestId(Integer testId) {
// this.testId = testId;
// }
//
// public Integer getTestType() {
// return testType;
// }
//
// public void setTestType(Integer testType) {
// this.testType = testType;
// }
//
// public String getQuestion() {
// return question;
// }
//
// public void setQuestion(String question) {
// this.question = question;
// }
//
// public String getAnswer() {
// return answer;
// }
//
// public void setAnswer(String answer) {
// this.answer = answer;
// }
//
// public String getAnswerA() {
// return answerA;
// }
//
// public void setAnswerA(String answerA) {
// this.answerA = answerA;
// }
//
// public String getAnswerB() {
// return answerB;
// }
//
// public void setAnswerB(String answerB) {
// this.answerB = answerB;
// }
//
// public String getAnswerC() {
// return answerC;
// }
//
// public void setAnswerC(String answerC) {
// this.answerC = answerC;
// }
//
// public String getAnswerD() {
// return answerD;
// }
//
// public void setAnswerD(String answerD) {
// this.answerD = answerD;
// }
//
// public String getAnswerE() {
// return answerE;
// }
//
// public void setAnswerE(String answerE) {
// this.answerE = answerE;
// }
//
// public String getAnswerF() {
// return answerF;
// }
//
// public void setAnswerF(String answerF) {
// this.answerF = answerF;
// }
//
// public String getAnswerG() {
// return answerG;
// }
//
// public void setAnswerG(String answerG) {
// this.answerG = answerG;
// }
//
// @Override
// public String toString() {
// return "Test{" +
// "testId=" + testId +
// ", testType=" + testType +
// ", question='" + question + '\'' +
// ", answer='" + answer + '\'' +
// ", answerA='" + answerA + '\'' +
// ", answerB='" + answerB + '\'' +
// ", answerC='" + answerC + '\'' +
// ", answerD='" + answerD + '\'' +
// ", answerE='" + answerE + '\'' +
// ", answerF='" + answerF + '\'' +
// ", answerG='" + answerG + '\'' +
// ", explain='" + explain + '\'' +
// '}';
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.vv.androidreview.R;
import com.vv.androidreview.entity.Test; | /*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.ui.view;
/**
* Author:Vv on .
* Mail:envyfan@qq.com
* Description:
*/
public class AnswerItem extends LinearLayout {
private TextView mChoice, mChoiceContent; | // Path: app/src/main/java/com/vv/androidreview/entity/Test.java
// public class Test extends BmobObject {
//
// private Integer testId;
// private Integer testType;
// private String question;
// private String answer;
// private String answerA;
// private String answerB;
// private String answerC;
// private String answerD;
// private String answerE;
// private String answerF;
// private String answerG;
//
// public String getExplain() {
// return explain;
// }
//
// public void setExplain(String explain) {
// this.explain = explain;
// }
//
// private String explain;
//
//
// public Integer getTestId() {
// return testId;
// }
//
// public void setTestId(Integer testId) {
// this.testId = testId;
// }
//
// public Integer getTestType() {
// return testType;
// }
//
// public void setTestType(Integer testType) {
// this.testType = testType;
// }
//
// public String getQuestion() {
// return question;
// }
//
// public void setQuestion(String question) {
// this.question = question;
// }
//
// public String getAnswer() {
// return answer;
// }
//
// public void setAnswer(String answer) {
// this.answer = answer;
// }
//
// public String getAnswerA() {
// return answerA;
// }
//
// public void setAnswerA(String answerA) {
// this.answerA = answerA;
// }
//
// public String getAnswerB() {
// return answerB;
// }
//
// public void setAnswerB(String answerB) {
// this.answerB = answerB;
// }
//
// public String getAnswerC() {
// return answerC;
// }
//
// public void setAnswerC(String answerC) {
// this.answerC = answerC;
// }
//
// public String getAnswerD() {
// return answerD;
// }
//
// public void setAnswerD(String answerD) {
// this.answerD = answerD;
// }
//
// public String getAnswerE() {
// return answerE;
// }
//
// public void setAnswerE(String answerE) {
// this.answerE = answerE;
// }
//
// public String getAnswerF() {
// return answerF;
// }
//
// public void setAnswerF(String answerF) {
// this.answerF = answerF;
// }
//
// public String getAnswerG() {
// return answerG;
// }
//
// public void setAnswerG(String answerG) {
// this.answerG = answerG;
// }
//
// @Override
// public String toString() {
// return "Test{" +
// "testId=" + testId +
// ", testType=" + testType +
// ", question='" + question + '\'' +
// ", answer='" + answer + '\'' +
// ", answerA='" + answerA + '\'' +
// ", answerB='" + answerB + '\'' +
// ", answerC='" + answerC + '\'' +
// ", answerD='" + answerD + '\'' +
// ", answerE='" + answerE + '\'' +
// ", answerF='" + answerF + '\'' +
// ", answerG='" + answerG + '\'' +
// ", explain='" + explain + '\'' +
// '}';
// }
// }
// Path: app/src/main/java/com/vv/androidreview/ui/view/AnswerItem.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.vv.androidreview.R;
import com.vv.androidreview.entity.Test;
/*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.ui.view;
/**
* Author:Vv on .
* Mail:envyfan@qq.com
* Description:
*/
public class AnswerItem extends LinearLayout {
private TextView mChoice, mChoiceContent; | private Test mTest; |
envyfan/AndroidReview | app/src/main/java/com/vv/androidreview/utils/WebViewHelper.java | // Path: app/src/main/java/com/vv/androidreview/entity/Content.java
// public class Content extends BmobObject {
//
// //标题
// private String title;
//
// //内容正文
// private String content;
//
// //作者
// private String author;
//
// //内容来源
// private String source;
//
// //创建者
// private String creater;
//
// //所属知识点
// private Point point;
//
// //简介
// private String small;
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// public Point getPoint() {
// return point;
// }
//
// public void setPoint(Point point) {
// this.point = point;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getSource() {
// return source;
// }
//
// public void setSource(String source) {
// this.source = source;
// }
//
// public String getCreater() {
// return creater;
// }
//
// public void setCreater(String creater) {
// this.creater = creater;
// }
// }
| import java.util.Map;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ZoomButtonsController;
import com.orhanobut.logger.Logger;
import com.vv.androidreview.entity.Content;
import java.util.List; | /*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.utils;
/**
* Author:Vv on 2015/7/21 16:20
* Mail:envyfan@qq.com
* Description:UI帮助类
*/
public class WebViewHelper {
public static final String LinkCss = "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/css/common.css\">";
public static final String LinkJS = "<script type=\"text/javascript\" src=\"file:///android_asset/js/common.js\"></script>";
public static final String Function_RemoveImageAttribute="<script> javascript:removeImageAttribute()</script>";
public static void initWebViewSettings(WebView webView) {
WebSettings settings = webView.getSettings();
//这个单位是SP
settings.setDefaultFontSize(15);
settings.setJavaScriptEnabled(true); //支持js
settings.setUseWideViewPort(false); //将图片调整到适合webview的大小
settings.setSupportZoom(true); //支持缩放
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//无论是否有网络,只要本地有缓存,都使用缓存。本地没有缓存时才从网络上获取。 这里的WebView主要是用来加载图片和解析Html文本
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//使超链接失效
return true;
}
});
}
/**
* 拼凑HTML的头部
*
* @return
*/
public static String getWebViewHead() {
StringBuffer htmlHead = new StringBuffer();
htmlHead.append("<head>");
htmlHead.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
htmlHead.append(WebViewHelper.setWebViewPadding(2, 2));
htmlHead.append(WebViewHelper.LinkCss);
htmlHead.append(WebViewHelper.LinkJS);
htmlHead.append("</head>");
return htmlHead.toString();
}
| // Path: app/src/main/java/com/vv/androidreview/entity/Content.java
// public class Content extends BmobObject {
//
// //标题
// private String title;
//
// //内容正文
// private String content;
//
// //作者
// private String author;
//
// //内容来源
// private String source;
//
// //创建者
// private String creater;
//
// //所属知识点
// private Point point;
//
// //简介
// private String small;
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// public Point getPoint() {
// return point;
// }
//
// public void setPoint(Point point) {
// this.point = point;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getSource() {
// return source;
// }
//
// public void setSource(String source) {
// this.source = source;
// }
//
// public String getCreater() {
// return creater;
// }
//
// public void setCreater(String creater) {
// this.creater = creater;
// }
// }
// Path: app/src/main/java/com/vv/androidreview/utils/WebViewHelper.java
import java.util.Map;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ZoomButtonsController;
import com.orhanobut.logger.Logger;
import com.vv.androidreview.entity.Content;
import java.util.List;
/*
* Copyright (c) 2016. Vv <envyfan@qq.com><http://www.v-sounds.com/>
*
* This file is part of AndroidReview (Android面试复习)
*
* AndroidReview is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidReview 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidReview. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vv.androidreview.utils;
/**
* Author:Vv on 2015/7/21 16:20
* Mail:envyfan@qq.com
* Description:UI帮助类
*/
public class WebViewHelper {
public static final String LinkCss = "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/css/common.css\">";
public static final String LinkJS = "<script type=\"text/javascript\" src=\"file:///android_asset/js/common.js\"></script>";
public static final String Function_RemoveImageAttribute="<script> javascript:removeImageAttribute()</script>";
public static void initWebViewSettings(WebView webView) {
WebSettings settings = webView.getSettings();
//这个单位是SP
settings.setDefaultFontSize(15);
settings.setJavaScriptEnabled(true); //支持js
settings.setUseWideViewPort(false); //将图片调整到适合webview的大小
settings.setSupportZoom(true); //支持缩放
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//无论是否有网络,只要本地有缓存,都使用缓存。本地没有缓存时才从网络上获取。 这里的WebView主要是用来加载图片和解析Html文本
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//使超链接失效
return true;
}
});
}
/**
* 拼凑HTML的头部
*
* @return
*/
public static String getWebViewHead() {
StringBuffer htmlHead = new StringBuffer();
htmlHead.append("<head>");
htmlHead.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
htmlHead.append(WebViewHelper.setWebViewPadding(2, 2));
htmlHead.append(WebViewHelper.LinkCss);
htmlHead.append(WebViewHelper.LinkJS);
htmlHead.append("</head>");
return htmlHead.toString();
}
| public static String getWebViewHtml(Content content) { |
SpongePowered/event-impl-gen | src/main/java/org/spongepowered/eventimplgen/factory/ClassNameProvider.java | // Path: src/main/java/org/spongepowered/eventimplgen/processor/EventGenOptions.java
// @Singleton
// public class EventGenOptions {
// static final Pattern COMMA_SPLIT = Pattern.compile(",", Pattern.LITERAL);
// static final Pattern COLON_SPLIT = Pattern.compile(":", Pattern.LITERAL);
//
// public static final String GENERATED_EVENT_FACTORY = "eventGenFactory";
//
// public static final String SORT_PRIORITY_PREFIX = "sortPriorityPrefix"; // default: original
// public static final String GROUPING_PREFIXES = "groupingPrefixes"; // <a>:<b>[,<a>:<b>]* default: from:to
//
// // these two take fully qualified names to annotations that should include or exclude a certain element from implementation generation
// public static final String INCLUSIVE_ANNOTATIONS = "inclusiveAnnotations"; // default: GenerateFactoryMethod
// public static final String EXCLUSIVE_ANNOTATIONS = "exclusiveAnnotations"; // default: NoFactoryMethod
//
// public static final String DEBUG = "eventGenDebug"; // default: false, whether to print debug logging
//
// private boolean validated;
// private boolean valid = true;
//
// private final Messager messager;
// private final Map<String, String> options;
//
// @Inject
// EventGenOptions(@ProcessorOptions final Map<String, String> options, final Messager messager) {
// this.options = options;
// this.messager = messager;
// }
//
// public String generatedEventFactory() {
// return Objects.requireNonNull(this.options.get(EventGenOptions.GENERATED_EVENT_FACTORY), "invalid state, factory name not provided");
// }
//
// public @Nullable String sortPriorityPrefix() {
// return this.options.getOrDefault(EventGenOptions.SORT_PRIORITY_PREFIX, "original");
// }
//
// public Map<String, String> groupingPrefixes() {
// final @Nullable String input = this.options.get(EventGenOptions.GROUPING_PREFIXES);
// if (input == null || input.isEmpty()) {
// return Collections.singletonMap("from", "to");
// }
//
// final Map<String, String> prefixes = new HashMap<>();
// for (final String pair : EventGenOptions.COMMA_SPLIT.split(input, -1)) {
// if (pair.isEmpty()) {
// continue;
// }
//
// final String[] values = EventGenOptions.COLON_SPLIT.split(pair, 2);
// if (values.length != 2) {
// this.messager.printMessage(
// Diagnostic.Kind.WARNING,
// String.format(
// "[event-impl-gen]: Invalid grouping prefix pair '%s' detected. Must be in the form <a>:<b>",
// pair
// )
// );
// prefixes.put(values[0], values[1]);
// }
// }
// return Collections.unmodifiableMap(prefixes);
// }
//
// public Set<String> inclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.INCLUSIVE_ANNOTATIONS, GenerateFactoryMethod.class.getCanonicalName());
// }
//
// public Set<String> exclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.EXCLUSIVE_ANNOTATIONS, NoFactoryMethod.class.getCanonicalName());
// }
//
// public boolean debug() {
// return Boolean.parseBoolean(this.options.getOrDefault(EventGenOptions.DEBUG, "false"));
// }
//
// private Set<String> commaSeparatedSet(final String key, final String defaultValue) {
// final @Nullable String input = this.options.get(key);
// if (input == null) {
// return Collections.singleton(defaultValue);
// }
// return new HashSet<>(Arrays.asList(EventGenOptions.COMMA_SPLIT.split(input, -1)));
// }
//
// /**
// * Ensure all options are accurate, and return `false` to skip processing if
// * any issues are detected.
// *
// * <p>This option can safely be called multiple times without printing
// * extraneous error messages.</p>
// *
// * @return whether all options are valid
// */
// public boolean validate() {
// if (this.validated) {
// return this.valid;
// }
//
// boolean valid = true;
// if (!this.options.containsKey(EventGenOptions.GENERATED_EVENT_FACTORY)) {
// this.messager.printMessage(Diagnostic.Kind.ERROR, "[event-impl-gen]: The " + EventGenOptions.GENERATED_EVENT_FACTORY + " option must be specified to generate a factory.");
// valid = false;
// }
//
// this.valid = valid;
// this.validated = true;
// return valid;
// }
// }
| import com.squareup.javapoet.ClassName;
import org.spongepowered.eventimplgen.processor.EventGenOptions;
import javax.inject.Inject;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.factory;
/**
* Provide class names for event interface generation.
*/
public class ClassNameProvider {
private final String targetPackage;
@Inject | // Path: src/main/java/org/spongepowered/eventimplgen/processor/EventGenOptions.java
// @Singleton
// public class EventGenOptions {
// static final Pattern COMMA_SPLIT = Pattern.compile(",", Pattern.LITERAL);
// static final Pattern COLON_SPLIT = Pattern.compile(":", Pattern.LITERAL);
//
// public static final String GENERATED_EVENT_FACTORY = "eventGenFactory";
//
// public static final String SORT_PRIORITY_PREFIX = "sortPriorityPrefix"; // default: original
// public static final String GROUPING_PREFIXES = "groupingPrefixes"; // <a>:<b>[,<a>:<b>]* default: from:to
//
// // these two take fully qualified names to annotations that should include or exclude a certain element from implementation generation
// public static final String INCLUSIVE_ANNOTATIONS = "inclusiveAnnotations"; // default: GenerateFactoryMethod
// public static final String EXCLUSIVE_ANNOTATIONS = "exclusiveAnnotations"; // default: NoFactoryMethod
//
// public static final String DEBUG = "eventGenDebug"; // default: false, whether to print debug logging
//
// private boolean validated;
// private boolean valid = true;
//
// private final Messager messager;
// private final Map<String, String> options;
//
// @Inject
// EventGenOptions(@ProcessorOptions final Map<String, String> options, final Messager messager) {
// this.options = options;
// this.messager = messager;
// }
//
// public String generatedEventFactory() {
// return Objects.requireNonNull(this.options.get(EventGenOptions.GENERATED_EVENT_FACTORY), "invalid state, factory name not provided");
// }
//
// public @Nullable String sortPriorityPrefix() {
// return this.options.getOrDefault(EventGenOptions.SORT_PRIORITY_PREFIX, "original");
// }
//
// public Map<String, String> groupingPrefixes() {
// final @Nullable String input = this.options.get(EventGenOptions.GROUPING_PREFIXES);
// if (input == null || input.isEmpty()) {
// return Collections.singletonMap("from", "to");
// }
//
// final Map<String, String> prefixes = new HashMap<>();
// for (final String pair : EventGenOptions.COMMA_SPLIT.split(input, -1)) {
// if (pair.isEmpty()) {
// continue;
// }
//
// final String[] values = EventGenOptions.COLON_SPLIT.split(pair, 2);
// if (values.length != 2) {
// this.messager.printMessage(
// Diagnostic.Kind.WARNING,
// String.format(
// "[event-impl-gen]: Invalid grouping prefix pair '%s' detected. Must be in the form <a>:<b>",
// pair
// )
// );
// prefixes.put(values[0], values[1]);
// }
// }
// return Collections.unmodifiableMap(prefixes);
// }
//
// public Set<String> inclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.INCLUSIVE_ANNOTATIONS, GenerateFactoryMethod.class.getCanonicalName());
// }
//
// public Set<String> exclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.EXCLUSIVE_ANNOTATIONS, NoFactoryMethod.class.getCanonicalName());
// }
//
// public boolean debug() {
// return Boolean.parseBoolean(this.options.getOrDefault(EventGenOptions.DEBUG, "false"));
// }
//
// private Set<String> commaSeparatedSet(final String key, final String defaultValue) {
// final @Nullable String input = this.options.get(key);
// if (input == null) {
// return Collections.singleton(defaultValue);
// }
// return new HashSet<>(Arrays.asList(EventGenOptions.COMMA_SPLIT.split(input, -1)));
// }
//
// /**
// * Ensure all options are accurate, and return `false` to skip processing if
// * any issues are detected.
// *
// * <p>This option can safely be called multiple times without printing
// * extraneous error messages.</p>
// *
// * @return whether all options are valid
// */
// public boolean validate() {
// if (this.validated) {
// return this.valid;
// }
//
// boolean valid = true;
// if (!this.options.containsKey(EventGenOptions.GENERATED_EVENT_FACTORY)) {
// this.messager.printMessage(Diagnostic.Kind.ERROR, "[event-impl-gen]: The " + EventGenOptions.GENERATED_EVENT_FACTORY + " option must be specified to generate a factory.");
// valid = false;
// }
//
// this.valid = valid;
// this.validated = true;
// return valid;
// }
// }
// Path: src/main/java/org/spongepowered/eventimplgen/factory/ClassNameProvider.java
import com.squareup.javapoet.ClassName;
import org.spongepowered.eventimplgen.processor.EventGenOptions;
import javax.inject.Inject;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.factory;
/**
* Provide class names for event interface generation.
*/
public class ClassNameProvider {
private final String targetPackage;
@Inject | public ClassNameProvider(final EventGenOptions options) { |
SpongePowered/event-impl-gen | test-data/src/test/java/test/event/TestEventFactoryTest.java | // Path: test-data/src/main/java/test/TypeToken.java
// public abstract class TypeToken<V> {
// private final Type type;
//
// protected TypeToken() {
// this.type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
// }
//
// public Type type() {
// return this.type;
// }
//
// public String typeName() {
// return this.type.getTypeName();
// }
//
// }
//
// Path: test-data/src/main/java/test/event/lifecycle/ConnectionEvent.java
// public interface ConnectionEvent extends Event {
//
// String name();
//
// Optional<Path> destination();
//
// void setDestination(final Path path);
//
// default int help() {
// return 5;
// }
//
// interface URL extends ConnectionEvent {
//
// java.net.URL source();
//
// interface Direct extends URL {}
// }
//
// }
//
// Path: test-data/src/main/java/test/event/lifecycle/NestedTest.java
// public interface NestedTest extends Event {
//
// int count();
//
// // void setCount(final int count);
//
// interface Pre extends NestedTest {
//
// }
//
// interface Post extends NestedTest {
//
// }
//
// }
| import java.nio.ByteBuffer;
import java.util.Collections;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import test.TypeToken;
import test.event.lifecycle.ConnectionEvent;
import test.event.lifecycle.NestedTest; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package test.event;
class TestEventFactoryTest {
@Test
void testTestEventFactory() {
// Most of our validation is that the test set compiles, this just executes a basic implementation. | // Path: test-data/src/main/java/test/TypeToken.java
// public abstract class TypeToken<V> {
// private final Type type;
//
// protected TypeToken() {
// this.type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
// }
//
// public Type type() {
// return this.type;
// }
//
// public String typeName() {
// return this.type.getTypeName();
// }
//
// }
//
// Path: test-data/src/main/java/test/event/lifecycle/ConnectionEvent.java
// public interface ConnectionEvent extends Event {
//
// String name();
//
// Optional<Path> destination();
//
// void setDestination(final Path path);
//
// default int help() {
// return 5;
// }
//
// interface URL extends ConnectionEvent {
//
// java.net.URL source();
//
// interface Direct extends URL {}
// }
//
// }
//
// Path: test-data/src/main/java/test/event/lifecycle/NestedTest.java
// public interface NestedTest extends Event {
//
// int count();
//
// // void setCount(final int count);
//
// interface Pre extends NestedTest {
//
// }
//
// interface Post extends NestedTest {
//
// }
//
// }
// Path: test-data/src/test/java/test/event/TestEventFactoryTest.java
import java.nio.ByteBuffer;
import java.util.Collections;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import test.TypeToken;
import test.event.lifecycle.ConnectionEvent;
import test.event.lifecycle.NestedTest;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package test.event;
class TestEventFactoryTest {
@Test
void testTestEventFactory() {
// Most of our validation is that the test set compiles, this just executes a basic implementation. | final NestedTest.Post conn = TestEventFactory.createNestedTestPost(false, 5); |
SpongePowered/event-impl-gen | src/main/java/org/spongepowered/eventimplgen/eventgencore/AccessorFirstStrategy.java | // Path: src/main/java/org/spongepowered/eventimplgen/signature/Descriptors.java
// public class Descriptors {
// public static final String TYPE_UNKNOWN = "eventImplGen/UNKNOWN";
// public static final String TYPE_ERROR = "eventImplGen/ERROR";
//
// private final Elements elements;
// private final Types types;
// private final TypeToDescriptorWriter descWriter;
//
// @Inject
// Descriptors(final Elements elements, final Types types, final TypeToDescriptorWriter descWriter) {
// this.elements = elements;
// this.types = types;
// this.descWriter = descWriter;
// }
//
// public String getDescriptor(final ExecutableElement method) {
// return this.getDescriptor((ExecutableType) method.asType(), true);
// }
//
// public String getDescriptor(final ExecutableType method, final boolean includeReturnType) {
// if (includeReturnType) {
// return method.accept(this.descWriter, new StringBuilder()).toString();
// } else {
// final StringBuilder builder = new StringBuilder();
// builder.append('(');
// for (final TypeMirror type : method.getParameterTypes()) {
// type.accept(this.descWriter, builder);
// }
// builder.append(")V");
// return builder.toString();
// }
// }
//
// public String getInternalName(TypeMirror name) {
// name = this.types.erasure(name);
// switch (name.getKind()) {
// case DECLARED:
// return this.getInternalName(this.elements.getBinaryName((TypeElement) ((DeclaredType) name).asElement()).toString());
// case ERROR:
// return Descriptors.TYPE_ERROR;
// default:
// return Descriptors.TYPE_UNKNOWN;
// }
// }
//
// public String getInternalName(final String name) {
// return name.replace('.', '/');
// }
//
// }
| import dagger.assisted.Assisted;
import dagger.assisted.AssistedFactory;
import dagger.assisted.AssistedInject;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.eventimplgen.signature.Descriptors;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.eventgencore;
/**
*
* Finds properties by enumerating accessors and then later finding the
* closest matching mutator.
*/
public class AccessorFirstStrategy implements PropertySearchStrategy {
private static final Pattern ACCESSOR = Pattern.compile("^get([A-Z].*)");
private static final Pattern ACCESSOR_BOOL = Pattern.compile("^is([A-Z].*)");
private static final Pattern ACCESSOR_HAS = Pattern.compile("^has([A-Z].*)");
private static final Pattern ACCESSOR_KEEPS = Pattern.compile("^(keeps[A-Z].*)");
private static final Pattern MUTATOR = Pattern.compile("^set([A-Z].*)");
| // Path: src/main/java/org/spongepowered/eventimplgen/signature/Descriptors.java
// public class Descriptors {
// public static final String TYPE_UNKNOWN = "eventImplGen/UNKNOWN";
// public static final String TYPE_ERROR = "eventImplGen/ERROR";
//
// private final Elements elements;
// private final Types types;
// private final TypeToDescriptorWriter descWriter;
//
// @Inject
// Descriptors(final Elements elements, final Types types, final TypeToDescriptorWriter descWriter) {
// this.elements = elements;
// this.types = types;
// this.descWriter = descWriter;
// }
//
// public String getDescriptor(final ExecutableElement method) {
// return this.getDescriptor((ExecutableType) method.asType(), true);
// }
//
// public String getDescriptor(final ExecutableType method, final boolean includeReturnType) {
// if (includeReturnType) {
// return method.accept(this.descWriter, new StringBuilder()).toString();
// } else {
// final StringBuilder builder = new StringBuilder();
// builder.append('(');
// for (final TypeMirror type : method.getParameterTypes()) {
// type.accept(this.descWriter, builder);
// }
// builder.append(")V");
// return builder.toString();
// }
// }
//
// public String getInternalName(TypeMirror name) {
// name = this.types.erasure(name);
// switch (name.getKind()) {
// case DECLARED:
// return this.getInternalName(this.elements.getBinaryName((TypeElement) ((DeclaredType) name).asElement()).toString());
// case ERROR:
// return Descriptors.TYPE_ERROR;
// default:
// return Descriptors.TYPE_UNKNOWN;
// }
// }
//
// public String getInternalName(final String name) {
// return name.replace('.', '/');
// }
//
// }
// Path: src/main/java/org/spongepowered/eventimplgen/eventgencore/AccessorFirstStrategy.java
import dagger.assisted.Assisted;
import dagger.assisted.AssistedFactory;
import dagger.assisted.AssistedInject;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.eventimplgen.signature.Descriptors;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.eventgencore;
/**
*
* Finds properties by enumerating accessors and then later finding the
* closest matching mutator.
*/
public class AccessorFirstStrategy implements PropertySearchStrategy {
private static final Pattern ACCESSOR = Pattern.compile("^get([A-Z].*)");
private static final Pattern ACCESSOR_BOOL = Pattern.compile("^is([A-Z].*)");
private static final Pattern ACCESSOR_HAS = Pattern.compile("^has([A-Z].*)");
private static final Pattern ACCESSOR_KEEPS = Pattern.compile("^(keeps[A-Z].*)");
private static final Pattern MUTATOR = Pattern.compile("^set([A-Z].*)");
| private final Descriptors descriptors; |
SpongePowered/event-impl-gen | test-data/src/main/java/test/event/lifecycle/CriterionEvent.java | // Path: test-data/src/main/java/test/event/Event.java
// @NoFactoryMethod
// public interface Event {
//
// default String version() {
// return "dingbats";
// }
//
// boolean cancelled();
//
// void setCancelled(final boolean cancelled);
//
// }
//
// Path: test-data/src/main/java/test/event/GenericEvent.java
// @NoFactoryMethod
// public interface GenericEvent<T> extends Event {
//
// TypeToken<T> type();
//
// }
| import test.event.Event;
import test.event.GenericEvent;
import java.nio.Buffer;
import java.util.List; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package test.event.lifecycle;
public interface CriterionEvent extends Event {
List<String> triggers();
void setTriggers(final List<String> triggers);
CharSequence name();
void setName(final CharSequence name);
interface Register extends CriterionEvent {
}
| // Path: test-data/src/main/java/test/event/Event.java
// @NoFactoryMethod
// public interface Event {
//
// default String version() {
// return "dingbats";
// }
//
// boolean cancelled();
//
// void setCancelled(final boolean cancelled);
//
// }
//
// Path: test-data/src/main/java/test/event/GenericEvent.java
// @NoFactoryMethod
// public interface GenericEvent<T> extends Event {
//
// TypeToken<T> type();
//
// }
// Path: test-data/src/main/java/test/event/lifecycle/CriterionEvent.java
import test.event.Event;
import test.event.GenericEvent;
import java.nio.Buffer;
import java.util.List;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package test.event.lifecycle;
public interface CriterionEvent extends Event {
List<String> triggers();
void setTriggers(final List<String> triggers);
CharSequence name();
void setName(final CharSequence name);
interface Register extends CriterionEvent {
}
| interface Trigger<C extends Buffer> extends CriterionEvent, GenericEvent<C> { |
SpongePowered/event-impl-gen | src/main/java/org/spongepowered/eventimplgen/eventgencore/PropertySorter.java | // Path: src/main/java/org/spongepowered/eventimplgen/processor/EventGenOptions.java
// @Singleton
// public class EventGenOptions {
// static final Pattern COMMA_SPLIT = Pattern.compile(",", Pattern.LITERAL);
// static final Pattern COLON_SPLIT = Pattern.compile(":", Pattern.LITERAL);
//
// public static final String GENERATED_EVENT_FACTORY = "eventGenFactory";
//
// public static final String SORT_PRIORITY_PREFIX = "sortPriorityPrefix"; // default: original
// public static final String GROUPING_PREFIXES = "groupingPrefixes"; // <a>:<b>[,<a>:<b>]* default: from:to
//
// // these two take fully qualified names to annotations that should include or exclude a certain element from implementation generation
// public static final String INCLUSIVE_ANNOTATIONS = "inclusiveAnnotations"; // default: GenerateFactoryMethod
// public static final String EXCLUSIVE_ANNOTATIONS = "exclusiveAnnotations"; // default: NoFactoryMethod
//
// public static final String DEBUG = "eventGenDebug"; // default: false, whether to print debug logging
//
// private boolean validated;
// private boolean valid = true;
//
// private final Messager messager;
// private final Map<String, String> options;
//
// @Inject
// EventGenOptions(@ProcessorOptions final Map<String, String> options, final Messager messager) {
// this.options = options;
// this.messager = messager;
// }
//
// public String generatedEventFactory() {
// return Objects.requireNonNull(this.options.get(EventGenOptions.GENERATED_EVENT_FACTORY), "invalid state, factory name not provided");
// }
//
// public @Nullable String sortPriorityPrefix() {
// return this.options.getOrDefault(EventGenOptions.SORT_PRIORITY_PREFIX, "original");
// }
//
// public Map<String, String> groupingPrefixes() {
// final @Nullable String input = this.options.get(EventGenOptions.GROUPING_PREFIXES);
// if (input == null || input.isEmpty()) {
// return Collections.singletonMap("from", "to");
// }
//
// final Map<String, String> prefixes = new HashMap<>();
// for (final String pair : EventGenOptions.COMMA_SPLIT.split(input, -1)) {
// if (pair.isEmpty()) {
// continue;
// }
//
// final String[] values = EventGenOptions.COLON_SPLIT.split(pair, 2);
// if (values.length != 2) {
// this.messager.printMessage(
// Diagnostic.Kind.WARNING,
// String.format(
// "[event-impl-gen]: Invalid grouping prefix pair '%s' detected. Must be in the form <a>:<b>",
// pair
// )
// );
// prefixes.put(values[0], values[1]);
// }
// }
// return Collections.unmodifiableMap(prefixes);
// }
//
// public Set<String> inclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.INCLUSIVE_ANNOTATIONS, GenerateFactoryMethod.class.getCanonicalName());
// }
//
// public Set<String> exclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.EXCLUSIVE_ANNOTATIONS, NoFactoryMethod.class.getCanonicalName());
// }
//
// public boolean debug() {
// return Boolean.parseBoolean(this.options.getOrDefault(EventGenOptions.DEBUG, "false"));
// }
//
// private Set<String> commaSeparatedSet(final String key, final String defaultValue) {
// final @Nullable String input = this.options.get(key);
// if (input == null) {
// return Collections.singleton(defaultValue);
// }
// return new HashSet<>(Arrays.asList(EventGenOptions.COMMA_SPLIT.split(input, -1)));
// }
//
// /**
// * Ensure all options are accurate, and return `false` to skip processing if
// * any issues are detected.
// *
// * <p>This option can safely be called multiple times without printing
// * extraneous error messages.</p>
// *
// * @return whether all options are valid
// */
// public boolean validate() {
// if (this.validated) {
// return this.valid;
// }
//
// boolean valid = true;
// if (!this.options.containsKey(EventGenOptions.GENERATED_EVENT_FACTORY)) {
// this.messager.printMessage(Diagnostic.Kind.ERROR, "[event-impl-gen]: The " + EventGenOptions.GENERATED_EVENT_FACTORY + " option must be specified to generate a factory.");
// valid = false;
// }
//
// this.valid = valid;
// this.validated = true;
// return valid;
// }
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.lang.model.util.Types;
import org.spongepowered.api.util.annotation.eventgen.AbsoluteSortPosition;
import org.spongepowered.eventimplgen.processor.EventGenOptions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.eventgencore;
public class PropertySorter {
private final String prefix;
private final Map<String, String> groupingPrefixes;
private final Types types;
@Inject | // Path: src/main/java/org/spongepowered/eventimplgen/processor/EventGenOptions.java
// @Singleton
// public class EventGenOptions {
// static final Pattern COMMA_SPLIT = Pattern.compile(",", Pattern.LITERAL);
// static final Pattern COLON_SPLIT = Pattern.compile(":", Pattern.LITERAL);
//
// public static final String GENERATED_EVENT_FACTORY = "eventGenFactory";
//
// public static final String SORT_PRIORITY_PREFIX = "sortPriorityPrefix"; // default: original
// public static final String GROUPING_PREFIXES = "groupingPrefixes"; // <a>:<b>[,<a>:<b>]* default: from:to
//
// // these two take fully qualified names to annotations that should include or exclude a certain element from implementation generation
// public static final String INCLUSIVE_ANNOTATIONS = "inclusiveAnnotations"; // default: GenerateFactoryMethod
// public static final String EXCLUSIVE_ANNOTATIONS = "exclusiveAnnotations"; // default: NoFactoryMethod
//
// public static final String DEBUG = "eventGenDebug"; // default: false, whether to print debug logging
//
// private boolean validated;
// private boolean valid = true;
//
// private final Messager messager;
// private final Map<String, String> options;
//
// @Inject
// EventGenOptions(@ProcessorOptions final Map<String, String> options, final Messager messager) {
// this.options = options;
// this.messager = messager;
// }
//
// public String generatedEventFactory() {
// return Objects.requireNonNull(this.options.get(EventGenOptions.GENERATED_EVENT_FACTORY), "invalid state, factory name not provided");
// }
//
// public @Nullable String sortPriorityPrefix() {
// return this.options.getOrDefault(EventGenOptions.SORT_PRIORITY_PREFIX, "original");
// }
//
// public Map<String, String> groupingPrefixes() {
// final @Nullable String input = this.options.get(EventGenOptions.GROUPING_PREFIXES);
// if (input == null || input.isEmpty()) {
// return Collections.singletonMap("from", "to");
// }
//
// final Map<String, String> prefixes = new HashMap<>();
// for (final String pair : EventGenOptions.COMMA_SPLIT.split(input, -1)) {
// if (pair.isEmpty()) {
// continue;
// }
//
// final String[] values = EventGenOptions.COLON_SPLIT.split(pair, 2);
// if (values.length != 2) {
// this.messager.printMessage(
// Diagnostic.Kind.WARNING,
// String.format(
// "[event-impl-gen]: Invalid grouping prefix pair '%s' detected. Must be in the form <a>:<b>",
// pair
// )
// );
// prefixes.put(values[0], values[1]);
// }
// }
// return Collections.unmodifiableMap(prefixes);
// }
//
// public Set<String> inclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.INCLUSIVE_ANNOTATIONS, GenerateFactoryMethod.class.getCanonicalName());
// }
//
// public Set<String> exclusiveAnnotations() {
// return this.commaSeparatedSet(EventGenOptions.EXCLUSIVE_ANNOTATIONS, NoFactoryMethod.class.getCanonicalName());
// }
//
// public boolean debug() {
// return Boolean.parseBoolean(this.options.getOrDefault(EventGenOptions.DEBUG, "false"));
// }
//
// private Set<String> commaSeparatedSet(final String key, final String defaultValue) {
// final @Nullable String input = this.options.get(key);
// if (input == null) {
// return Collections.singleton(defaultValue);
// }
// return new HashSet<>(Arrays.asList(EventGenOptions.COMMA_SPLIT.split(input, -1)));
// }
//
// /**
// * Ensure all options are accurate, and return `false` to skip processing if
// * any issues are detected.
// *
// * <p>This option can safely be called multiple times without printing
// * extraneous error messages.</p>
// *
// * @return whether all options are valid
// */
// public boolean validate() {
// if (this.validated) {
// return this.valid;
// }
//
// boolean valid = true;
// if (!this.options.containsKey(EventGenOptions.GENERATED_EVENT_FACTORY)) {
// this.messager.printMessage(Diagnostic.Kind.ERROR, "[event-impl-gen]: The " + EventGenOptions.GENERATED_EVENT_FACTORY + " option must be specified to generate a factory.");
// valid = false;
// }
//
// this.valid = valid;
// this.validated = true;
// return valid;
// }
// }
// Path: src/main/java/org/spongepowered/eventimplgen/eventgencore/PropertySorter.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.lang.model.util.Types;
import org.spongepowered.api.util.annotation.eventgen.AbsoluteSortPosition;
import org.spongepowered.eventimplgen.processor.EventGenOptions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.eventgencore;
public class PropertySorter {
private final String prefix;
private final Map<String, String> groupingPrefixes;
private final Types types;
@Inject | PropertySorter(final Types types, final EventGenOptions options) { |
SpongePowered/event-impl-gen | src/main/java/org/spongepowered/eventimplgen/processor/EventScanner.java | // Path: src/main/java/org/spongepowered/eventimplgen/AnnotationUtils.java
// public final class AnnotationUtils {
//
// private AnnotationUtils() {
// }
//
// @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
// public static <T> T getValue(final AnnotationMirror anno, final String key) {
// if (anno == null) {
// return null;
// }
//
// for (final Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : anno.getElementValues().entrySet()) {
// if (element.getKey().getSimpleName().contentEquals(key)) {
// return (T) element.getValue().getValue();
// }
// }
// return null;
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final Class<? extends Annotation> clazz) {
// return AnnotationUtils.getAnnotation(type, clazz.getName());
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final String name) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString().equals(name)) {
// return annotation;
// }
// }
// return null;
// }
//
// public static boolean containsAnnotation(final AnnotatedConstruct type, final Set<String> looking) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (looking.contains(((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/org/spongepowered/eventimplgen/eventgencore/PropertySearchStrategy.java
// public interface PropertySearchStrategy {
//
// /**
// * Enumerate a list of properties on a class, considering super types
// * and implemented interfaces.
// *
// * <p>The returned list is sorted lexographically by property name</p>
// *
// * @param type The class
// * @return A set of properties
// */
// List<Property> findProperties(final TypeElement type);
//
// }
| import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.util.annotation.eventgen.FactoryMethod;
import org.spongepowered.api.util.annotation.eventgen.internal.GeneratedEvent;
import org.spongepowered.eventimplgen.AnnotationUtils;
import org.spongepowered.eventimplgen.eventgencore.PropertySearchStrategy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.QualifiedNameable;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.processor;
public class EventScanner {
static final Pattern DOT_SPLIT = Pattern.compile("\\.");
private final Set<String> inclusiveAnnotations;
private final Set<String> exclusiveAnnotations;
private final boolean debugMode;
private final Types types;
private final Elements elements;
private final Messager messager; | // Path: src/main/java/org/spongepowered/eventimplgen/AnnotationUtils.java
// public final class AnnotationUtils {
//
// private AnnotationUtils() {
// }
//
// @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
// public static <T> T getValue(final AnnotationMirror anno, final String key) {
// if (anno == null) {
// return null;
// }
//
// for (final Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : anno.getElementValues().entrySet()) {
// if (element.getKey().getSimpleName().contentEquals(key)) {
// return (T) element.getValue().getValue();
// }
// }
// return null;
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final Class<? extends Annotation> clazz) {
// return AnnotationUtils.getAnnotation(type, clazz.getName());
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final String name) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString().equals(name)) {
// return annotation;
// }
// }
// return null;
// }
//
// public static boolean containsAnnotation(final AnnotatedConstruct type, final Set<String> looking) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (looking.contains(((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/org/spongepowered/eventimplgen/eventgencore/PropertySearchStrategy.java
// public interface PropertySearchStrategy {
//
// /**
// * Enumerate a list of properties on a class, considering super types
// * and implemented interfaces.
// *
// * <p>The returned list is sorted lexographically by property name</p>
// *
// * @param type The class
// * @return A set of properties
// */
// List<Property> findProperties(final TypeElement type);
//
// }
// Path: src/main/java/org/spongepowered/eventimplgen/processor/EventScanner.java
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.util.annotation.eventgen.FactoryMethod;
import org.spongepowered.api.util.annotation.eventgen.internal.GeneratedEvent;
import org.spongepowered.eventimplgen.AnnotationUtils;
import org.spongepowered.eventimplgen.eventgencore.PropertySearchStrategy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.QualifiedNameable;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.eventimplgen.processor;
public class EventScanner {
static final Pattern DOT_SPLIT = Pattern.compile("\\.");
private final Set<String> inclusiveAnnotations;
private final Set<String> exclusiveAnnotations;
private final boolean debugMode;
private final Types types;
private final Elements elements;
private final Messager messager; | private final PropertySearchStrategy strategy; |
SpongePowered/event-impl-gen | src/main/java/org/spongepowered/eventimplgen/processor/EventScanner.java | // Path: src/main/java/org/spongepowered/eventimplgen/AnnotationUtils.java
// public final class AnnotationUtils {
//
// private AnnotationUtils() {
// }
//
// @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
// public static <T> T getValue(final AnnotationMirror anno, final String key) {
// if (anno == null) {
// return null;
// }
//
// for (final Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : anno.getElementValues().entrySet()) {
// if (element.getKey().getSimpleName().contentEquals(key)) {
// return (T) element.getValue().getValue();
// }
// }
// return null;
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final Class<? extends Annotation> clazz) {
// return AnnotationUtils.getAnnotation(type, clazz.getName());
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final String name) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString().equals(name)) {
// return annotation;
// }
// }
// return null;
// }
//
// public static boolean containsAnnotation(final AnnotatedConstruct type, final Set<String> looking) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (looking.contains(((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/org/spongepowered/eventimplgen/eventgencore/PropertySearchStrategy.java
// public interface PropertySearchStrategy {
//
// /**
// * Enumerate a list of properties on a class, considering super types
// * and implemented interfaces.
// *
// * <p>The returned list is sorted lexographically by property name</p>
// *
// * @param type The class
// * @return A set of properties
// */
// List<Property> findProperties(final TypeElement type);
//
// }
| import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.util.annotation.eventgen.FactoryMethod;
import org.spongepowered.api.util.annotation.eventgen.internal.GeneratedEvent;
import org.spongepowered.eventimplgen.AnnotationUtils;
import org.spongepowered.eventimplgen.eventgencore.PropertySearchStrategy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.QualifiedNameable;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic; | this.messager.printMessage(Diagnostic.Kind.NOTE, "Generating for event " + event.getSimpleName());
}
final Set<Element> extraOriginating;
if (pointer.parent == null) {
extraOriginating = Collections.emptySet();
} else {
extraOriginating = new HashSet<>();
OriginatedElement collector = pointer.parent;
do {
extraOriginating.add(collector.element);
} while ((collector = collector.parent) != null);
}
consumer.propertyFound(event, this.strategy.findProperties(event), extraOriginating);
consumer.forwardedMethods(this.findForwardedMethods(event));
}
}
} else if (active.getKind() == ElementKind.CLASS
&& active.getAnnotation(GeneratedEvent.class) != null) {
continue; // these implementation classes are indirectly annotated, but because we generated them we can ignore them.
} else if (active.getKind() != ElementKind.ENUM) { // implicitly exclude enums, they are commonly declared nested in event interfaces
this.messager.printMessage(Diagnostic.Kind.ERROR, "This element (" + active.getKind() + " " + active.getSimpleName() + ") was "
+ "annotated directly or transitively, but it is not a package or interface", active);
failed = true;
}
}
return !failed;
}
public boolean hasExclusiveAnnotation(final Element candidate) { | // Path: src/main/java/org/spongepowered/eventimplgen/AnnotationUtils.java
// public final class AnnotationUtils {
//
// private AnnotationUtils() {
// }
//
// @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
// public static <T> T getValue(final AnnotationMirror anno, final String key) {
// if (anno == null) {
// return null;
// }
//
// for (final Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : anno.getElementValues().entrySet()) {
// if (element.getKey().getSimpleName().contentEquals(key)) {
// return (T) element.getValue().getValue();
// }
// }
// return null;
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final Class<? extends Annotation> clazz) {
// return AnnotationUtils.getAnnotation(type, clazz.getName());
// }
//
// public static @Nullable AnnotationMirror getAnnotation(final AnnotatedConstruct type, final String name) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString().equals(name)) {
// return annotation;
// }
// }
// return null;
// }
//
// public static boolean containsAnnotation(final AnnotatedConstruct type, final Set<String> looking) {
// for (final AnnotationMirror annotation : type.getAnnotationMirrors()) {
// if (looking.contains(((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/org/spongepowered/eventimplgen/eventgencore/PropertySearchStrategy.java
// public interface PropertySearchStrategy {
//
// /**
// * Enumerate a list of properties on a class, considering super types
// * and implemented interfaces.
// *
// * <p>The returned list is sorted lexographically by property name</p>
// *
// * @param type The class
// * @return A set of properties
// */
// List<Property> findProperties(final TypeElement type);
//
// }
// Path: src/main/java/org/spongepowered/eventimplgen/processor/EventScanner.java
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.util.annotation.eventgen.FactoryMethod;
import org.spongepowered.api.util.annotation.eventgen.internal.GeneratedEvent;
import org.spongepowered.eventimplgen.AnnotationUtils;
import org.spongepowered.eventimplgen.eventgencore.PropertySearchStrategy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.QualifiedNameable;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
this.messager.printMessage(Diagnostic.Kind.NOTE, "Generating for event " + event.getSimpleName());
}
final Set<Element> extraOriginating;
if (pointer.parent == null) {
extraOriginating = Collections.emptySet();
} else {
extraOriginating = new HashSet<>();
OriginatedElement collector = pointer.parent;
do {
extraOriginating.add(collector.element);
} while ((collector = collector.parent) != null);
}
consumer.propertyFound(event, this.strategy.findProperties(event), extraOriginating);
consumer.forwardedMethods(this.findForwardedMethods(event));
}
}
} else if (active.getKind() == ElementKind.CLASS
&& active.getAnnotation(GeneratedEvent.class) != null) {
continue; // these implementation classes are indirectly annotated, but because we generated them we can ignore them.
} else if (active.getKind() != ElementKind.ENUM) { // implicitly exclude enums, they are commonly declared nested in event interfaces
this.messager.printMessage(Diagnostic.Kind.ERROR, "This element (" + active.getKind() + " " + active.getSimpleName() + ") was "
+ "annotated directly or transitively, but it is not a package or interface", active);
failed = true;
}
}
return !failed;
}
public boolean hasExclusiveAnnotation(final Element candidate) { | return AnnotationUtils.containsAnnotation(candidate, this.exclusiveAnnotations); |
SpongePowered/event-impl-gen | test-data/src/main/java/test/event/GenericEvent.java | // Path: test-data/src/main/java/test/TypeToken.java
// public abstract class TypeToken<V> {
// private final Type type;
//
// protected TypeToken() {
// this.type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
// }
//
// public Type type() {
// return this.type;
// }
//
// public String typeName() {
// return this.type.getTypeName();
// }
//
// }
| import org.spongepowered.api.util.annotation.eventgen.NoFactoryMethod;
import test.TypeToken; | /*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package test.event;
@NoFactoryMethod
public interface GenericEvent<T> extends Event {
| // Path: test-data/src/main/java/test/TypeToken.java
// public abstract class TypeToken<V> {
// private final Type type;
//
// protected TypeToken() {
// this.type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
// }
//
// public Type type() {
// return this.type;
// }
//
// public String typeName() {
// return this.type.getTypeName();
// }
//
// }
// Path: test-data/src/main/java/test/event/GenericEvent.java
import org.spongepowered.api.util.annotation.eventgen.NoFactoryMethod;
import test.TypeToken;
/*
* This file is part of Event Implementation Generator, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package test.event;
@NoFactoryMethod
public interface GenericEvent<T> extends Event {
| TypeToken<T> type(); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/AbstractEmoteMessage.java | // Path: src/main/java/com/gikk/twirk/types/emote/Emote.java
// public interface Emote {
// /** Fetches the emotes ID as String. This became necessary after Twitch start
// * including other characters than numbers in emote IDs
// *
// * @return The emotes ID
// */
// String getEmoteIDString();
//
// /** A list of pairs on indices. Each pair is a BEGIN-END pair of a emote occurrence in the message.<br><br>
// *
// * For example, if the message is: {@code Kappa PogChamp Kappa}<br> the list for emote 'Kappa' will include these pairs:<ul>
// * <li> (0,5)
// * <li> (15,20)
// * </ul>
// *
// * @return The indices this emote takes up in the associated message
// */
// LinkedList<EmoteIndices> getIndices();
//
// /** The emote's pattern. For example: 'Kappa'
// *
// * @return The emote's pattern
// */
// String getPattern();
//
// /**Emote images can be downloaded from Twitch's server, and come in three
// * sizes. Use this method to get the address for the emote.
// *
// * @param imageSize Emotes comes in three sizes. Specify which size you want
// * @return The address for the emote's image
// */
// String getEmoteImageUrl(EMOTE_SIZE imageSize);
//
// /**Class for representing the beginning and end of an emote occurrence within a message
// *
// * @author Gikkman
// */
// class EmoteIndices{
// public final int beingIndex;
// public final int endIndex;
//
// public EmoteIndices(int begin, int end){
// this.beingIndex = begin;
// this.endIndex = end;
// }
//
// public String toString(){
// return "(" +beingIndex + "," + endIndex + ")";
// }
// }
// }
| import com.gikk.twirk.types.emote.Emote;
import java.util.List; | package com.gikk.twirk.types;
/**Interface for chat messages that might contain emotes
*
* @author Gikkman
*/
public interface AbstractEmoteMessage extends AbstractType{
/**Checks whether this message contains emotes or not
*
* @return {@code true} if the message contains emotes
*/
public boolean hasEmotes();
/**Fetches a list of all all emotes in this message. Each emote is encapsulated in a {@link Emote}.
* The list might be empty, if the message contained no emotes.
*
* @return List of emotes (might be empty)
*/ | // Path: src/main/java/com/gikk/twirk/types/emote/Emote.java
// public interface Emote {
// /** Fetches the emotes ID as String. This became necessary after Twitch start
// * including other characters than numbers in emote IDs
// *
// * @return The emotes ID
// */
// String getEmoteIDString();
//
// /** A list of pairs on indices. Each pair is a BEGIN-END pair of a emote occurrence in the message.<br><br>
// *
// * For example, if the message is: {@code Kappa PogChamp Kappa}<br> the list for emote 'Kappa' will include these pairs:<ul>
// * <li> (0,5)
// * <li> (15,20)
// * </ul>
// *
// * @return The indices this emote takes up in the associated message
// */
// LinkedList<EmoteIndices> getIndices();
//
// /** The emote's pattern. For example: 'Kappa'
// *
// * @return The emote's pattern
// */
// String getPattern();
//
// /**Emote images can be downloaded from Twitch's server, and come in three
// * sizes. Use this method to get the address for the emote.
// *
// * @param imageSize Emotes comes in three sizes. Specify which size you want
// * @return The address for the emote's image
// */
// String getEmoteImageUrl(EMOTE_SIZE imageSize);
//
// /**Class for representing the beginning and end of an emote occurrence within a message
// *
// * @author Gikkman
// */
// class EmoteIndices{
// public final int beingIndex;
// public final int endIndex;
//
// public EmoteIndices(int begin, int end){
// this.beingIndex = begin;
// this.endIndex = end;
// }
//
// public String toString(){
// return "(" +beingIndex + "," + endIndex + ")";
// }
// }
// }
// Path: src/main/java/com/gikk/twirk/types/AbstractEmoteMessage.java
import com.gikk.twirk.types.emote.Emote;
import java.util.List;
package com.gikk.twirk.types;
/**Interface for chat messages that might contain emotes
*
* @author Gikkman
*/
public interface AbstractEmoteMessage extends AbstractType{
/**Checks whether this message contains emotes or not
*
* @return {@code true} if the message contains emotes
*/
public boolean hasEmotes();
/**Fetches a list of all all emotes in this message. Each emote is encapsulated in a {@link Emote}.
* The list might be empty, if the message contained no emotes.
*
* @return List of emotes (might be empty)
*/ | public List<Emote> getEmotes(); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/roomstate/TestRoomstate.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.roomstate;
public class TestRoomstate {
private final static String JOIN = "@broadcaster-lang=;emote-only=0;r9k=0;slow=0;subs-only=0;followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_ON_MESSAGE = "@subs-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_OFF_MESSAGE = "@subs-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_ON_MESSAGE = "@r9k=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_OFF_MESSAGE = "@r9k=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_120_MESSAGE = "@slow=120 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_OFF_MESSAGE = "@slow=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_ON_MESSAGE = "@followers-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_OFF_MESSAGE = "@followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_ON_MESSAGE = "@emote-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_OFF_MESSAGE = "@emote-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
| // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
// Path: src/test/java/com/gikk/twirk/types/roomstate/TestRoomstate.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.roomstate;
public class TestRoomstate {
private final static String JOIN = "@broadcaster-lang=;emote-only=0;r9k=0;slow=0;subs-only=0;followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_ON_MESSAGE = "@subs-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_OFF_MESSAGE = "@subs-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_ON_MESSAGE = "@r9k=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_OFF_MESSAGE = "@r9k=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_120_MESSAGE = "@slow=120 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_OFF_MESSAGE = "@slow=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_ON_MESSAGE = "@followers-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_OFF_MESSAGE = "@followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_ON_MESSAGE = "@emote-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_OFF_MESSAGE = "@emote-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
| public static void test(Consumer<String> twirkIn, TestConsumer<Roomstate> roomstateTest) throws Exception { |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/roomstate/TestRoomstate.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.roomstate;
public class TestRoomstate {
private final static String JOIN = "@broadcaster-lang=;emote-only=0;r9k=0;slow=0;subs-only=0;followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_ON_MESSAGE = "@subs-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_OFF_MESSAGE = "@subs-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_ON_MESSAGE = "@r9k=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_OFF_MESSAGE = "@r9k=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_120_MESSAGE = "@slow=120 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_OFF_MESSAGE = "@slow=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_ON_MESSAGE = "@followers-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_OFF_MESSAGE = "@followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_ON_MESSAGE = "@emote-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_OFF_MESSAGE = "@emote-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
public static void test(Consumer<String> twirkIn, TestConsumer<Roomstate> roomstateTest) throws Exception { | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
// Path: src/test/java/com/gikk/twirk/types/roomstate/TestRoomstate.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.roomstate;
public class TestRoomstate {
private final static String JOIN = "@broadcaster-lang=;emote-only=0;r9k=0;slow=0;subs-only=0;followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_ON_MESSAGE = "@subs-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SUB_MODE_OFF_MESSAGE = "@subs-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_ON_MESSAGE = "@r9k=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String R9K_MODE_OFF_MESSAGE = "@r9k=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_120_MESSAGE = "@slow=120 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String SLOW_MODE_OFF_MESSAGE = "@slow=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_ON_MESSAGE = "@followers-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String FOLLOWERS_MODE_OFF_MESSAGE = "@followers-only=-1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_ON_MESSAGE = "@emote-only=1 :tmi.twitch.tv ROOMSTATE #gikkman";
private final static String EMOTE_ONLY_MODE_OFF_MESSAGE = "@emote-only=0 :tmi.twitch.tv ROOMSTATE #gikkman";
public static void test(Consumer<String> twirkIn, TestConsumer<Roomstate> roomstateTest) throws Exception { | TestResult t1 = roomstateTest.assign(TestRoomstate::testJoin); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/emote/EmoteImpl.java | // Path: src/main/java/com/gikk/twirk/enums/EMOTE_SIZE.java
// public enum EMOTE_SIZE{
// SMALL("/1.0"),
// MEDIUM("/2.0"),
// LARGE("/3.0");
// public final String value;
// private EMOTE_SIZE(String val){ this.value = val; }
// }
| import com.gikk.twirk.enums.EMOTE_SIZE;
import java.util.LinkedList; | return this;
}
public EmoteImpl setPattern(String pattern){
this.pattern = pattern;
return this;
}
public EmoteImpl addIndices(int begin, int end){
this.indices.add( new EmoteIndices(begin, end) );
return this;
}
@Override
public String getEmoteIDString() {
return emoteIDString;
}
@Override
public String getPattern() {
return pattern;
}
@Override
public LinkedList<EmoteIndices> getIndices() {
return indices;
}
@Override | // Path: src/main/java/com/gikk/twirk/enums/EMOTE_SIZE.java
// public enum EMOTE_SIZE{
// SMALL("/1.0"),
// MEDIUM("/2.0"),
// LARGE("/3.0");
// public final String value;
// private EMOTE_SIZE(String val){ this.value = val; }
// }
// Path: src/main/java/com/gikk/twirk/types/emote/EmoteImpl.java
import com.gikk.twirk.enums.EMOTE_SIZE;
import java.util.LinkedList;
return this;
}
public EmoteImpl setPattern(String pattern){
this.pattern = pattern;
return this;
}
public EmoteImpl addIndices(int begin, int end){
this.indices.add( new EmoteIndices(begin, end) );
return this;
}
@Override
public String getEmoteIDString() {
return emoteIDString;
}
@Override
public String getPattern() {
return pattern;
}
@Override
public LinkedList<EmoteIndices> getIndices() {
return indices;
}
@Override | public String getEmoteImageUrl(EMOTE_SIZE imageSize){ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/twitchMessage/TestMessage.java | // Path: src/test/java/com/gikk/twirk/TestBiConsumer.java
// public class TestBiConsumer<T, U> {
// private BiFunction<T,U, Boolean> test;
// private TestResult res;
//
// public TestResult assign(BiFunction<T, U, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T t, U u){
// if(test != null) {
// res.complete(test.apply(t, u));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUser.java
// public interface TwitchUser {
//
// /**Retrieves this user's user name. This is the name the user logs in to
// * Twitch with
// *
// * @return The user's user name
// */
// public String getUserName();
//
// /**Retrieves this user's display name, as displayed in Twitch chat
// *
// * @return The user's display name
// */
// public String getDisplayName();
//
// /**Retrieves info whether this user is the owner of this channel or not
// *
// * @return {@code true} if the user is the owner, {@code false} if not
// */
// public boolean isOwner();
//
// /**Retrieves info whether this user is a mod in this channel or not
// *
// * @return {@code true} if the user is mod, {@code false} if not
// */
// public boolean isMod();
//
// /**Retrieves info whether this user has turbo or not
// *
// * @return {@code true} if the user has turbo, {@code false} if not
// */
// public boolean isTurbo();
//
// /**Retrieves info whether this user is a sub to this channel or not
// *
// * @return {@code true} if the user is a sub, {@code false} if not
// */
// public boolean isSub();
//
// /**Retrieves this users {@link USER_TYPE} <br>
// * There are seven USER_TYPEs: OWNER, MOD, GLOBAL_MOD, ADMIN, STAFF, SUBSCRIBER and DEFAULT.
// *
// * @return The user's USER_TYPE
// */
// public USER_TYPE getUserType();
//
// /**Retrieves this users display color, as seen in Twitch chat.<br>
// * The color is a hexadecimal number.
// *
// * @return The users display color, as a hex number
// */
// public int getColor();
//
// /**Retrieves the users set of badges in Twitch chat. A badge looks like this: <br>
// * {@code broadcaster/1} <br><br>
// *
// * There are several different badges, such as {@code broadcaster/1}, {@code turbo/1} and so on. I do
// * not know all of them explicitly, or what to do with them.
// *
// * TODO: Find out more about badges
// *
// * @return Arrays of strings, representing this users badges. Might be empty if user has none.
// */
// public String[] getBadges();
//
// /**Retrieves this user's unique user ID. This ID is decided by Twitch, and will
// * always be the same for the same user
// *
// * @return The users unique user ID
// */
// public long getUserID();
// }
| import com.gikk.twirk.TestBiConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.types.users.TwitchUser;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.twitchMessage;
public class TestMessage {
final static String USER_MESSAGE_NO_EMOTE = "@badges=;color=;display-name=Gikkman;emotes=;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage 조선말";
final static String USER_MESSAGE_WITH_EMOTE = "@badges=;color=#FF69B4;display-name=Gikklol;emotes=86:10-19;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikklol!gikklol@gikklol.tmi.twitch.tv PRIVMSG #gikkman :beefin it BibleThump";
| // Path: src/test/java/com/gikk/twirk/TestBiConsumer.java
// public class TestBiConsumer<T, U> {
// private BiFunction<T,U, Boolean> test;
// private TestResult res;
//
// public TestResult assign(BiFunction<T, U, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T t, U u){
// if(test != null) {
// res.complete(test.apply(t, u));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUser.java
// public interface TwitchUser {
//
// /**Retrieves this user's user name. This is the name the user logs in to
// * Twitch with
// *
// * @return The user's user name
// */
// public String getUserName();
//
// /**Retrieves this user's display name, as displayed in Twitch chat
// *
// * @return The user's display name
// */
// public String getDisplayName();
//
// /**Retrieves info whether this user is the owner of this channel or not
// *
// * @return {@code true} if the user is the owner, {@code false} if not
// */
// public boolean isOwner();
//
// /**Retrieves info whether this user is a mod in this channel or not
// *
// * @return {@code true} if the user is mod, {@code false} if not
// */
// public boolean isMod();
//
// /**Retrieves info whether this user has turbo or not
// *
// * @return {@code true} if the user has turbo, {@code false} if not
// */
// public boolean isTurbo();
//
// /**Retrieves info whether this user is a sub to this channel or not
// *
// * @return {@code true} if the user is a sub, {@code false} if not
// */
// public boolean isSub();
//
// /**Retrieves this users {@link USER_TYPE} <br>
// * There are seven USER_TYPEs: OWNER, MOD, GLOBAL_MOD, ADMIN, STAFF, SUBSCRIBER and DEFAULT.
// *
// * @return The user's USER_TYPE
// */
// public USER_TYPE getUserType();
//
// /**Retrieves this users display color, as seen in Twitch chat.<br>
// * The color is a hexadecimal number.
// *
// * @return The users display color, as a hex number
// */
// public int getColor();
//
// /**Retrieves the users set of badges in Twitch chat. A badge looks like this: <br>
// * {@code broadcaster/1} <br><br>
// *
// * There are several different badges, such as {@code broadcaster/1}, {@code turbo/1} and so on. I do
// * not know all of them explicitly, or what to do with them.
// *
// * TODO: Find out more about badges
// *
// * @return Arrays of strings, representing this users badges. Might be empty if user has none.
// */
// public String[] getBadges();
//
// /**Retrieves this user's unique user ID. This ID is decided by Twitch, and will
// * always be the same for the same user
// *
// * @return The users unique user ID
// */
// public long getUserID();
// }
// Path: src/test/java/com/gikk/twirk/types/twitchMessage/TestMessage.java
import com.gikk.twirk.TestBiConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.types.users.TwitchUser;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.twitchMessage;
public class TestMessage {
final static String USER_MESSAGE_NO_EMOTE = "@badges=;color=;display-name=Gikkman;emotes=;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage 조선말";
final static String USER_MESSAGE_WITH_EMOTE = "@badges=;color=#FF69B4;display-name=Gikklol;emotes=86:10-19;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikklol!gikklol@gikklol.tmi.twitch.tv PRIVMSG #gikkman :beefin it BibleThump";
| public static void testPrivMsg(Consumer<String> twirkInput, TestBiConsumer<TwitchUser, TwitchMessage> test ) throws Exception{ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/twitchMessage/TestMessage.java | // Path: src/test/java/com/gikk/twirk/TestBiConsumer.java
// public class TestBiConsumer<T, U> {
// private BiFunction<T,U, Boolean> test;
// private TestResult res;
//
// public TestResult assign(BiFunction<T, U, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T t, U u){
// if(test != null) {
// res.complete(test.apply(t, u));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUser.java
// public interface TwitchUser {
//
// /**Retrieves this user's user name. This is the name the user logs in to
// * Twitch with
// *
// * @return The user's user name
// */
// public String getUserName();
//
// /**Retrieves this user's display name, as displayed in Twitch chat
// *
// * @return The user's display name
// */
// public String getDisplayName();
//
// /**Retrieves info whether this user is the owner of this channel or not
// *
// * @return {@code true} if the user is the owner, {@code false} if not
// */
// public boolean isOwner();
//
// /**Retrieves info whether this user is a mod in this channel or not
// *
// * @return {@code true} if the user is mod, {@code false} if not
// */
// public boolean isMod();
//
// /**Retrieves info whether this user has turbo or not
// *
// * @return {@code true} if the user has turbo, {@code false} if not
// */
// public boolean isTurbo();
//
// /**Retrieves info whether this user is a sub to this channel or not
// *
// * @return {@code true} if the user is a sub, {@code false} if not
// */
// public boolean isSub();
//
// /**Retrieves this users {@link USER_TYPE} <br>
// * There are seven USER_TYPEs: OWNER, MOD, GLOBAL_MOD, ADMIN, STAFF, SUBSCRIBER and DEFAULT.
// *
// * @return The user's USER_TYPE
// */
// public USER_TYPE getUserType();
//
// /**Retrieves this users display color, as seen in Twitch chat.<br>
// * The color is a hexadecimal number.
// *
// * @return The users display color, as a hex number
// */
// public int getColor();
//
// /**Retrieves the users set of badges in Twitch chat. A badge looks like this: <br>
// * {@code broadcaster/1} <br><br>
// *
// * There are several different badges, such as {@code broadcaster/1}, {@code turbo/1} and so on. I do
// * not know all of them explicitly, or what to do with them.
// *
// * TODO: Find out more about badges
// *
// * @return Arrays of strings, representing this users badges. Might be empty if user has none.
// */
// public String[] getBadges();
//
// /**Retrieves this user's unique user ID. This ID is decided by Twitch, and will
// * always be the same for the same user
// *
// * @return The users unique user ID
// */
// public long getUserID();
// }
| import com.gikk.twirk.TestBiConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.types.users.TwitchUser;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.twitchMessage;
public class TestMessage {
final static String USER_MESSAGE_NO_EMOTE = "@badges=;color=;display-name=Gikkman;emotes=;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage 조선말";
final static String USER_MESSAGE_WITH_EMOTE = "@badges=;color=#FF69B4;display-name=Gikklol;emotes=86:10-19;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikklol!gikklol@gikklol.tmi.twitch.tv PRIVMSG #gikkman :beefin it BibleThump";
| // Path: src/test/java/com/gikk/twirk/TestBiConsumer.java
// public class TestBiConsumer<T, U> {
// private BiFunction<T,U, Boolean> test;
// private TestResult res;
//
// public TestResult assign(BiFunction<T, U, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T t, U u){
// if(test != null) {
// res.complete(test.apply(t, u));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUser.java
// public interface TwitchUser {
//
// /**Retrieves this user's user name. This is the name the user logs in to
// * Twitch with
// *
// * @return The user's user name
// */
// public String getUserName();
//
// /**Retrieves this user's display name, as displayed in Twitch chat
// *
// * @return The user's display name
// */
// public String getDisplayName();
//
// /**Retrieves info whether this user is the owner of this channel or not
// *
// * @return {@code true} if the user is the owner, {@code false} if not
// */
// public boolean isOwner();
//
// /**Retrieves info whether this user is a mod in this channel or not
// *
// * @return {@code true} if the user is mod, {@code false} if not
// */
// public boolean isMod();
//
// /**Retrieves info whether this user has turbo or not
// *
// * @return {@code true} if the user has turbo, {@code false} if not
// */
// public boolean isTurbo();
//
// /**Retrieves info whether this user is a sub to this channel or not
// *
// * @return {@code true} if the user is a sub, {@code false} if not
// */
// public boolean isSub();
//
// /**Retrieves this users {@link USER_TYPE} <br>
// * There are seven USER_TYPEs: OWNER, MOD, GLOBAL_MOD, ADMIN, STAFF, SUBSCRIBER and DEFAULT.
// *
// * @return The user's USER_TYPE
// */
// public USER_TYPE getUserType();
//
// /**Retrieves this users display color, as seen in Twitch chat.<br>
// * The color is a hexadecimal number.
// *
// * @return The users display color, as a hex number
// */
// public int getColor();
//
// /**Retrieves the users set of badges in Twitch chat. A badge looks like this: <br>
// * {@code broadcaster/1} <br><br>
// *
// * There are several different badges, such as {@code broadcaster/1}, {@code turbo/1} and so on. I do
// * not know all of them explicitly, or what to do with them.
// *
// * TODO: Find out more about badges
// *
// * @return Arrays of strings, representing this users badges. Might be empty if user has none.
// */
// public String[] getBadges();
//
// /**Retrieves this user's unique user ID. This ID is decided by Twitch, and will
// * always be the same for the same user
// *
// * @return The users unique user ID
// */
// public long getUserID();
// }
// Path: src/test/java/com/gikk/twirk/types/twitchMessage/TestMessage.java
import com.gikk.twirk.TestBiConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.types.users.TwitchUser;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.twitchMessage;
public class TestMessage {
final static String USER_MESSAGE_NO_EMOTE = "@badges=;color=;display-name=Gikkman;emotes=;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage 조선말";
final static String USER_MESSAGE_WITH_EMOTE = "@badges=;color=#FF69B4;display-name=Gikklol;emotes=86:10-19;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikklol!gikklol@gikklol.tmi.twitch.tv PRIVMSG #gikkman :beefin it BibleThump";
| public static void testPrivMsg(Consumer<String> twirkInput, TestBiConsumer<TwitchUser, TwitchMessage> test ) throws Exception{ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/twitchMessage/TestMessage.java | // Path: src/test/java/com/gikk/twirk/TestBiConsumer.java
// public class TestBiConsumer<T, U> {
// private BiFunction<T,U, Boolean> test;
// private TestResult res;
//
// public TestResult assign(BiFunction<T, U, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T t, U u){
// if(test != null) {
// res.complete(test.apply(t, u));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUser.java
// public interface TwitchUser {
//
// /**Retrieves this user's user name. This is the name the user logs in to
// * Twitch with
// *
// * @return The user's user name
// */
// public String getUserName();
//
// /**Retrieves this user's display name, as displayed in Twitch chat
// *
// * @return The user's display name
// */
// public String getDisplayName();
//
// /**Retrieves info whether this user is the owner of this channel or not
// *
// * @return {@code true} if the user is the owner, {@code false} if not
// */
// public boolean isOwner();
//
// /**Retrieves info whether this user is a mod in this channel or not
// *
// * @return {@code true} if the user is mod, {@code false} if not
// */
// public boolean isMod();
//
// /**Retrieves info whether this user has turbo or not
// *
// * @return {@code true} if the user has turbo, {@code false} if not
// */
// public boolean isTurbo();
//
// /**Retrieves info whether this user is a sub to this channel or not
// *
// * @return {@code true} if the user is a sub, {@code false} if not
// */
// public boolean isSub();
//
// /**Retrieves this users {@link USER_TYPE} <br>
// * There are seven USER_TYPEs: OWNER, MOD, GLOBAL_MOD, ADMIN, STAFF, SUBSCRIBER and DEFAULT.
// *
// * @return The user's USER_TYPE
// */
// public USER_TYPE getUserType();
//
// /**Retrieves this users display color, as seen in Twitch chat.<br>
// * The color is a hexadecimal number.
// *
// * @return The users display color, as a hex number
// */
// public int getColor();
//
// /**Retrieves the users set of badges in Twitch chat. A badge looks like this: <br>
// * {@code broadcaster/1} <br><br>
// *
// * There are several different badges, such as {@code broadcaster/1}, {@code turbo/1} and so on. I do
// * not know all of them explicitly, or what to do with them.
// *
// * TODO: Find out more about badges
// *
// * @return Arrays of strings, representing this users badges. Might be empty if user has none.
// */
// public String[] getBadges();
//
// /**Retrieves this user's unique user ID. This ID is decided by Twitch, and will
// * always be the same for the same user
// *
// * @return The users unique user ID
// */
// public long getUserID();
// }
| import com.gikk.twirk.TestBiConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.types.users.TwitchUser;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.twitchMessage;
public class TestMessage {
final static String USER_MESSAGE_NO_EMOTE = "@badges=;color=;display-name=Gikkman;emotes=;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage 조선말";
final static String USER_MESSAGE_WITH_EMOTE = "@badges=;color=#FF69B4;display-name=Gikklol;emotes=86:10-19;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikklol!gikklol@gikklol.tmi.twitch.tv PRIVMSG #gikkman :beefin it BibleThump";
public static void testPrivMsg(Consumer<String> twirkInput, TestBiConsumer<TwitchUser, TwitchMessage> test ) throws Exception{ | // Path: src/test/java/com/gikk/twirk/TestBiConsumer.java
// public class TestBiConsumer<T, U> {
// private BiFunction<T,U, Boolean> test;
// private TestResult res;
//
// public TestResult assign(BiFunction<T, U, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T t, U u){
// if(test != null) {
// res.complete(test.apply(t, u));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUser.java
// public interface TwitchUser {
//
// /**Retrieves this user's user name. This is the name the user logs in to
// * Twitch with
// *
// * @return The user's user name
// */
// public String getUserName();
//
// /**Retrieves this user's display name, as displayed in Twitch chat
// *
// * @return The user's display name
// */
// public String getDisplayName();
//
// /**Retrieves info whether this user is the owner of this channel or not
// *
// * @return {@code true} if the user is the owner, {@code false} if not
// */
// public boolean isOwner();
//
// /**Retrieves info whether this user is a mod in this channel or not
// *
// * @return {@code true} if the user is mod, {@code false} if not
// */
// public boolean isMod();
//
// /**Retrieves info whether this user has turbo or not
// *
// * @return {@code true} if the user has turbo, {@code false} if not
// */
// public boolean isTurbo();
//
// /**Retrieves info whether this user is a sub to this channel or not
// *
// * @return {@code true} if the user is a sub, {@code false} if not
// */
// public boolean isSub();
//
// /**Retrieves this users {@link USER_TYPE} <br>
// * There are seven USER_TYPEs: OWNER, MOD, GLOBAL_MOD, ADMIN, STAFF, SUBSCRIBER and DEFAULT.
// *
// * @return The user's USER_TYPE
// */
// public USER_TYPE getUserType();
//
// /**Retrieves this users display color, as seen in Twitch chat.<br>
// * The color is a hexadecimal number.
// *
// * @return The users display color, as a hex number
// */
// public int getColor();
//
// /**Retrieves the users set of badges in Twitch chat. A badge looks like this: <br>
// * {@code broadcaster/1} <br><br>
// *
// * There are several different badges, such as {@code broadcaster/1}, {@code turbo/1} and so on. I do
// * not know all of them explicitly, or what to do with them.
// *
// * TODO: Find out more about badges
// *
// * @return Arrays of strings, representing this users badges. Might be empty if user has none.
// */
// public String[] getBadges();
//
// /**Retrieves this user's unique user ID. This ID is decided by Twitch, and will
// * always be the same for the same user
// *
// * @return The users unique user ID
// */
// public long getUserID();
// }
// Path: src/test/java/com/gikk/twirk/types/twitchMessage/TestMessage.java
import com.gikk.twirk.TestBiConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.types.users.TwitchUser;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.twitchMessage;
public class TestMessage {
final static String USER_MESSAGE_NO_EMOTE = "@badges=;color=;display-name=Gikkman;emotes=;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage 조선말";
final static String USER_MESSAGE_WITH_EMOTE = "@badges=;color=#FF69B4;display-name=Gikklol;emotes=86:10-19;mod=0;room-id=31974228;subscriber=0;turbo=0;user-id=27658385;user-type= :gikklol!gikklol@gikklol.tmi.twitch.tv PRIVMSG #gikkman :beefin it BibleThump";
public static void testPrivMsg(Consumer<String> twirkInput, TestBiConsumer<TwitchUser, TwitchMessage> test ) throws Exception{ | TestResult t1 = test.assign(TestMessage::testUserMessageNoEmote); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/roomstate/RoomstateBuilder.java | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
| import com.gikk.twirk.types.twitchMessage.TwitchMessage; | package com.gikk.twirk.types.roomstate;
/**Constructs a {@link Roomstate} object. To create a {@link Roomstate} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface RoomstateBuilder {
public static RoomstateBuilder getDefault() {
return new DefaultRoomstateBuilder();
}
/**Constructs a new {@link Roomstate} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Roomstate} object.
* Make sure that the COMMAND of the message equals "ROOMSTATE"
*
* @param message The message we received from Twitch
* @return A {@link Roomstate}, or <code>null</code> if a {@link Roomstate} could not be created
*/ | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
// Path: src/main/java/com/gikk/twirk/types/roomstate/RoomstateBuilder.java
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
package com.gikk.twirk.types.roomstate;
/**Constructs a {@link Roomstate} object. To create a {@link Roomstate} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface RoomstateBuilder {
public static RoomstateBuilder getDefault() {
return new DefaultRoomstateBuilder();
}
/**Constructs a new {@link Roomstate} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Roomstate} object.
* Make sure that the COMMAND of the message equals "ROOMSTATE"
*
* @param message The message we received from Twitch
* @return A {@link Roomstate}, or <code>null</code> if a {@link Roomstate} could not be created
*/ | public Roomstate build(TwitchMessage message); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/hostTarget/TestHostTarget.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/HOSTTARGET_MODE.java
// public enum HOSTTARGET_MODE {
// /**Indicates that we started hosting a channel*/
// START,
// /**Indicates that we stopped hosting a channel*/
// STOP }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.HOSTTARGET_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.hostTarget;
public class TestHostTarget {
private final static String START_HOST = ":tmi.twitch.tv HOSTTARGET #gikkman :gikkbot 1"; //Gikkman host Gikkbot for 1 viewer
private final static String STOP_HOST_NO_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :-"; //Gikkbot stopped hosting for 0 viewers
private final static String STOP_HOST_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :- 5"; //Gikkbot stopped hosting for 0 viewers
| // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/HOSTTARGET_MODE.java
// public enum HOSTTARGET_MODE {
// /**Indicates that we started hosting a channel*/
// START,
// /**Indicates that we stopped hosting a channel*/
// STOP }
// Path: src/test/java/com/gikk/twirk/types/hostTarget/TestHostTarget.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.HOSTTARGET_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.hostTarget;
public class TestHostTarget {
private final static String START_HOST = ":tmi.twitch.tv HOSTTARGET #gikkman :gikkbot 1"; //Gikkman host Gikkbot for 1 viewer
private final static String STOP_HOST_NO_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :-"; //Gikkbot stopped hosting for 0 viewers
private final static String STOP_HOST_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :- 5"; //Gikkbot stopped hosting for 0 viewers
| public static void test(Consumer<String> twirkInput, TestConsumer<HostTarget> test ) throws Exception{ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/hostTarget/TestHostTarget.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/HOSTTARGET_MODE.java
// public enum HOSTTARGET_MODE {
// /**Indicates that we started hosting a channel*/
// START,
// /**Indicates that we stopped hosting a channel*/
// STOP }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.HOSTTARGET_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.hostTarget;
public class TestHostTarget {
private final static String START_HOST = ":tmi.twitch.tv HOSTTARGET #gikkman :gikkbot 1"; //Gikkman host Gikkbot for 1 viewer
private final static String STOP_HOST_NO_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :-"; //Gikkbot stopped hosting for 0 viewers
private final static String STOP_HOST_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :- 5"; //Gikkbot stopped hosting for 0 viewers
public static void test(Consumer<String> twirkInput, TestConsumer<HostTarget> test ) throws Exception{ | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/HOSTTARGET_MODE.java
// public enum HOSTTARGET_MODE {
// /**Indicates that we started hosting a channel*/
// START,
// /**Indicates that we stopped hosting a channel*/
// STOP }
// Path: src/test/java/com/gikk/twirk/types/hostTarget/TestHostTarget.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.HOSTTARGET_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.hostTarget;
public class TestHostTarget {
private final static String START_HOST = ":tmi.twitch.tv HOSTTARGET #gikkman :gikkbot 1"; //Gikkman host Gikkbot for 1 viewer
private final static String STOP_HOST_NO_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :-"; //Gikkbot stopped hosting for 0 viewers
private final static String STOP_HOST_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :- 5"; //Gikkbot stopped hosting for 0 viewers
public static void test(Consumer<String> twirkInput, TestConsumer<HostTarget> test ) throws Exception{ | TestResult resStart = test.assign(TestHostTarget::testStart); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/hostTarget/TestHostTarget.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/HOSTTARGET_MODE.java
// public enum HOSTTARGET_MODE {
// /**Indicates that we started hosting a channel*/
// START,
// /**Indicates that we stopped hosting a channel*/
// STOP }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.HOSTTARGET_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.hostTarget;
public class TestHostTarget {
private final static String START_HOST = ":tmi.twitch.tv HOSTTARGET #gikkman :gikkbot 1"; //Gikkman host Gikkbot for 1 viewer
private final static String STOP_HOST_NO_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :-"; //Gikkbot stopped hosting for 0 viewers
private final static String STOP_HOST_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :- 5"; //Gikkbot stopped hosting for 0 viewers
public static void test(Consumer<String> twirkInput, TestConsumer<HostTarget> test ) throws Exception{
TestResult resStart = test.assign(TestHostTarget::testStart);
twirkInput.accept(START_HOST);
resStart.await();
TestResult resStopNoView = test.assign(TestHostTarget::testStopNoView);
twirkInput.accept(STOP_HOST_NO_VIEWERS);
resStopNoView.await();
TestResult resStopView = test.assign(TestHostTarget::testStopView);
twirkInput.accept(STOP_HOST_VIEWERS);
resStopView.await();
}
static boolean testStart(HostTarget host){ | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/HOSTTARGET_MODE.java
// public enum HOSTTARGET_MODE {
// /**Indicates that we started hosting a channel*/
// START,
// /**Indicates that we stopped hosting a channel*/
// STOP }
// Path: src/test/java/com/gikk/twirk/types/hostTarget/TestHostTarget.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.HOSTTARGET_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.hostTarget;
public class TestHostTarget {
private final static String START_HOST = ":tmi.twitch.tv HOSTTARGET #gikkman :gikkbot 1"; //Gikkman host Gikkbot for 1 viewer
private final static String STOP_HOST_NO_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :-"; //Gikkbot stopped hosting for 0 viewers
private final static String STOP_HOST_VIEWERS = ":tmi.twitch.tv HOSTTARGET #gikkman :- 5"; //Gikkbot stopped hosting for 0 viewers
public static void test(Consumer<String> twirkInput, TestConsumer<HostTarget> test ) throws Exception{
TestResult resStart = test.assign(TestHostTarget::testStart);
twirkInput.accept(START_HOST);
resStart.await();
TestResult resStopNoView = test.assign(TestHostTarget::testStopNoView);
twirkInput.accept(STOP_HOST_NO_VIEWERS);
resStopNoView.await();
TestResult resStopView = test.assign(TestHostTarget::testStopView);
twirkInput.accept(STOP_HOST_VIEWERS);
resStopView.await();
}
static boolean testStart(HostTarget host){ | doTest(host, START_HOST, HOSTTARGET_MODE.START, 1, "gikkbot" ); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/notice/TestNotice.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/NOTICE_EVENT.java
// public enum NOTICE_EVENT {
// /** [User] is already banned in this room. */
// ALREADY_BANNED("already_banned"),
// /** This room is not in emote-only mode. */
// ALREADY_EMOTES_ONLY_OFF("already_emote_only_off"),
// /** This room is already in emote-only mode. */
// ALREADY_EMOTES_ONLY_ON("already_emote_only_on"),
// /** This room is not in r9k mode. */
// ALREADY_R9K_OFF("already_r9k_off"),
// /** This room is already in r9k mode. */
// ALREADY_R9K_ON("already_r9k_on"),
// /** This room is not in subscribers-only mode. */
// ALREADY_SUBS_OFF("already_subs_off"),
// /** This room is already in subscribers-only mode. */
// ALREADY_SUBS_ON("already_subs_on"),
// /** This channel is hosting [Channel}. */
// BAD_HOST_HOSTING("bad_host_hosting"),
// /** [User] is not banned from this room. (See #getTargetDisplayName())*/
// BAD_UNBAN_NO_BAN("bad_unban_no_ban"),
// /** [User] is banned from this room. */
// BAN_SUCCESS("ban_success"),
// /** This room is no longer in emote-only mode. */
// EMOTE_ONLY_OFF("emote_only_off"),
// /** This room is now in emote-only mode. */
// EMOTE_ONLY_ON("emote_only_on"),
// /** Exited host mode. */
// HOST_OFF("host_off"),
// /** Now hosting [Channel]. */
// HOST_ON("host_on"),
// /** There are [Number] host commands remaining this half hour. */
// HOST_REMAINING("hosts_remaining"),
// /** This channel is suspended. */
// MESSAGE_CHANNEL_SUSPENDED("msg_channel_suspended"),
// /**This room is no longer in r9k mode. */
// R9K_OFF("r9k_off"),
// /** This room is now in r9k mode. */
// R9K_ON("r9k_on"),
// /** This room is no longer in slow mode. */
// SLOW_OFF("slow_off"),
// /** This room is now in slow mode. You may send messages every [Seconds] seconds.*/
// SLOW_ON("slow_on"),
// /** This room is no longer in subscribers-only mode. */
// SUBSCRIBER_MODE_OFF("subs_off"),
// /** This room is now in subscribers-only mode. */
// SUBSCRIBER_MODE_ON("subs_on"),
// /** [User] has been timed out for [Seconds] seconds. */
// TIMEOUT_SUCCESS("timeout_success"),
// /** [User] is no longer banned from this chat room. */
// UNBAN_SUCCESS("unban_success"),
// /** Unrecognized command: [Command] */
// UNRECOGNIZED_COMMAND("unrecognized_cmd"),
//
// /**We default to this one if we do not recognize this NOTICE's event type. Since Twitch uses a lot of different undocumented
// * NOTICE types, there is need for a event type that works as a catch-all. <br>
// * Consider parsing the {@link Notice#getRawNoticeID()}.
// */
// OTHER("");
//
// private final String msgID;
// private NOTICE_EVENT(String msgID){
// this.msgID = msgID;
// }
//
// private final static Map<String, NOTICE_EVENT> mapping = new HashMap<>();
// static{
// for(NOTICE_EVENT n : values()){
// mapping.put(n.msgID, n);
// }
// }
//
// public static NOTICE_EVENT of(String msgID){
// return mapping.getOrDefault(msgID, OTHER);
// }
// };
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.NOTICE_EVENT;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.notice;
public class TestNotice {
private final static String SUB_MODE_ON_MESSAGE = "@msg-id=subs_on :tmi.twitch.tv NOTICE #gikkman :This room is now in subscribers-only mode.";
private final static String SUB_MODE_OFF_MESSAGE = "@msg-id=subs_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in subscribers-only mode.";
private final static String R9K_MODE_ON_MESSAGE = "@msg-id=r9k_on :tmi.twitch.tv NOTICE #gikkman :This room is now in r9k mode.";
private final static String R9K_MODE_OFF_MESSAGE = "@msg-id=r9k_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in r9k mode.";
private final static String CUSTOM_MESSAGE = "@msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #gikkman :This ma' message now.";
| // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/NOTICE_EVENT.java
// public enum NOTICE_EVENT {
// /** [User] is already banned in this room. */
// ALREADY_BANNED("already_banned"),
// /** This room is not in emote-only mode. */
// ALREADY_EMOTES_ONLY_OFF("already_emote_only_off"),
// /** This room is already in emote-only mode. */
// ALREADY_EMOTES_ONLY_ON("already_emote_only_on"),
// /** This room is not in r9k mode. */
// ALREADY_R9K_OFF("already_r9k_off"),
// /** This room is already in r9k mode. */
// ALREADY_R9K_ON("already_r9k_on"),
// /** This room is not in subscribers-only mode. */
// ALREADY_SUBS_OFF("already_subs_off"),
// /** This room is already in subscribers-only mode. */
// ALREADY_SUBS_ON("already_subs_on"),
// /** This channel is hosting [Channel}. */
// BAD_HOST_HOSTING("bad_host_hosting"),
// /** [User] is not banned from this room. (See #getTargetDisplayName())*/
// BAD_UNBAN_NO_BAN("bad_unban_no_ban"),
// /** [User] is banned from this room. */
// BAN_SUCCESS("ban_success"),
// /** This room is no longer in emote-only mode. */
// EMOTE_ONLY_OFF("emote_only_off"),
// /** This room is now in emote-only mode. */
// EMOTE_ONLY_ON("emote_only_on"),
// /** Exited host mode. */
// HOST_OFF("host_off"),
// /** Now hosting [Channel]. */
// HOST_ON("host_on"),
// /** There are [Number] host commands remaining this half hour. */
// HOST_REMAINING("hosts_remaining"),
// /** This channel is suspended. */
// MESSAGE_CHANNEL_SUSPENDED("msg_channel_suspended"),
// /**This room is no longer in r9k mode. */
// R9K_OFF("r9k_off"),
// /** This room is now in r9k mode. */
// R9K_ON("r9k_on"),
// /** This room is no longer in slow mode. */
// SLOW_OFF("slow_off"),
// /** This room is now in slow mode. You may send messages every [Seconds] seconds.*/
// SLOW_ON("slow_on"),
// /** This room is no longer in subscribers-only mode. */
// SUBSCRIBER_MODE_OFF("subs_off"),
// /** This room is now in subscribers-only mode. */
// SUBSCRIBER_MODE_ON("subs_on"),
// /** [User] has been timed out for [Seconds] seconds. */
// TIMEOUT_SUCCESS("timeout_success"),
// /** [User] is no longer banned from this chat room. */
// UNBAN_SUCCESS("unban_success"),
// /** Unrecognized command: [Command] */
// UNRECOGNIZED_COMMAND("unrecognized_cmd"),
//
// /**We default to this one if we do not recognize this NOTICE's event type. Since Twitch uses a lot of different undocumented
// * NOTICE types, there is need for a event type that works as a catch-all. <br>
// * Consider parsing the {@link Notice#getRawNoticeID()}.
// */
// OTHER("");
//
// private final String msgID;
// private NOTICE_EVENT(String msgID){
// this.msgID = msgID;
// }
//
// private final static Map<String, NOTICE_EVENT> mapping = new HashMap<>();
// static{
// for(NOTICE_EVENT n : values()){
// mapping.put(n.msgID, n);
// }
// }
//
// public static NOTICE_EVENT of(String msgID){
// return mapping.getOrDefault(msgID, OTHER);
// }
// };
// Path: src/test/java/com/gikk/twirk/types/notice/TestNotice.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.NOTICE_EVENT;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.notice;
public class TestNotice {
private final static String SUB_MODE_ON_MESSAGE = "@msg-id=subs_on :tmi.twitch.tv NOTICE #gikkman :This room is now in subscribers-only mode.";
private final static String SUB_MODE_OFF_MESSAGE = "@msg-id=subs_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in subscribers-only mode.";
private final static String R9K_MODE_ON_MESSAGE = "@msg-id=r9k_on :tmi.twitch.tv NOTICE #gikkman :This room is now in r9k mode.";
private final static String R9K_MODE_OFF_MESSAGE = "@msg-id=r9k_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in r9k mode.";
private final static String CUSTOM_MESSAGE = "@msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #gikkman :This ma' message now.";
| public static void test(Consumer<String> twirkInput, TestConsumer<Notice> test ) throws Exception{ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/notice/TestNotice.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/NOTICE_EVENT.java
// public enum NOTICE_EVENT {
// /** [User] is already banned in this room. */
// ALREADY_BANNED("already_banned"),
// /** This room is not in emote-only mode. */
// ALREADY_EMOTES_ONLY_OFF("already_emote_only_off"),
// /** This room is already in emote-only mode. */
// ALREADY_EMOTES_ONLY_ON("already_emote_only_on"),
// /** This room is not in r9k mode. */
// ALREADY_R9K_OFF("already_r9k_off"),
// /** This room is already in r9k mode. */
// ALREADY_R9K_ON("already_r9k_on"),
// /** This room is not in subscribers-only mode. */
// ALREADY_SUBS_OFF("already_subs_off"),
// /** This room is already in subscribers-only mode. */
// ALREADY_SUBS_ON("already_subs_on"),
// /** This channel is hosting [Channel}. */
// BAD_HOST_HOSTING("bad_host_hosting"),
// /** [User] is not banned from this room. (See #getTargetDisplayName())*/
// BAD_UNBAN_NO_BAN("bad_unban_no_ban"),
// /** [User] is banned from this room. */
// BAN_SUCCESS("ban_success"),
// /** This room is no longer in emote-only mode. */
// EMOTE_ONLY_OFF("emote_only_off"),
// /** This room is now in emote-only mode. */
// EMOTE_ONLY_ON("emote_only_on"),
// /** Exited host mode. */
// HOST_OFF("host_off"),
// /** Now hosting [Channel]. */
// HOST_ON("host_on"),
// /** There are [Number] host commands remaining this half hour. */
// HOST_REMAINING("hosts_remaining"),
// /** This channel is suspended. */
// MESSAGE_CHANNEL_SUSPENDED("msg_channel_suspended"),
// /**This room is no longer in r9k mode. */
// R9K_OFF("r9k_off"),
// /** This room is now in r9k mode. */
// R9K_ON("r9k_on"),
// /** This room is no longer in slow mode. */
// SLOW_OFF("slow_off"),
// /** This room is now in slow mode. You may send messages every [Seconds] seconds.*/
// SLOW_ON("slow_on"),
// /** This room is no longer in subscribers-only mode. */
// SUBSCRIBER_MODE_OFF("subs_off"),
// /** This room is now in subscribers-only mode. */
// SUBSCRIBER_MODE_ON("subs_on"),
// /** [User] has been timed out for [Seconds] seconds. */
// TIMEOUT_SUCCESS("timeout_success"),
// /** [User] is no longer banned from this chat room. */
// UNBAN_SUCCESS("unban_success"),
// /** Unrecognized command: [Command] */
// UNRECOGNIZED_COMMAND("unrecognized_cmd"),
//
// /**We default to this one if we do not recognize this NOTICE's event type. Since Twitch uses a lot of different undocumented
// * NOTICE types, there is need for a event type that works as a catch-all. <br>
// * Consider parsing the {@link Notice#getRawNoticeID()}.
// */
// OTHER("");
//
// private final String msgID;
// private NOTICE_EVENT(String msgID){
// this.msgID = msgID;
// }
//
// private final static Map<String, NOTICE_EVENT> mapping = new HashMap<>();
// static{
// for(NOTICE_EVENT n : values()){
// mapping.put(n.msgID, n);
// }
// }
//
// public static NOTICE_EVENT of(String msgID){
// return mapping.getOrDefault(msgID, OTHER);
// }
// };
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.NOTICE_EVENT;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.notice;
public class TestNotice {
private final static String SUB_MODE_ON_MESSAGE = "@msg-id=subs_on :tmi.twitch.tv NOTICE #gikkman :This room is now in subscribers-only mode.";
private final static String SUB_MODE_OFF_MESSAGE = "@msg-id=subs_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in subscribers-only mode.";
private final static String R9K_MODE_ON_MESSAGE = "@msg-id=r9k_on :tmi.twitch.tv NOTICE #gikkman :This room is now in r9k mode.";
private final static String R9K_MODE_OFF_MESSAGE = "@msg-id=r9k_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in r9k mode.";
private final static String CUSTOM_MESSAGE = "@msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #gikkman :This ma' message now.";
public static void test(Consumer<String> twirkInput, TestConsumer<Notice> test ) throws Exception{ | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/NOTICE_EVENT.java
// public enum NOTICE_EVENT {
// /** [User] is already banned in this room. */
// ALREADY_BANNED("already_banned"),
// /** This room is not in emote-only mode. */
// ALREADY_EMOTES_ONLY_OFF("already_emote_only_off"),
// /** This room is already in emote-only mode. */
// ALREADY_EMOTES_ONLY_ON("already_emote_only_on"),
// /** This room is not in r9k mode. */
// ALREADY_R9K_OFF("already_r9k_off"),
// /** This room is already in r9k mode. */
// ALREADY_R9K_ON("already_r9k_on"),
// /** This room is not in subscribers-only mode. */
// ALREADY_SUBS_OFF("already_subs_off"),
// /** This room is already in subscribers-only mode. */
// ALREADY_SUBS_ON("already_subs_on"),
// /** This channel is hosting [Channel}. */
// BAD_HOST_HOSTING("bad_host_hosting"),
// /** [User] is not banned from this room. (See #getTargetDisplayName())*/
// BAD_UNBAN_NO_BAN("bad_unban_no_ban"),
// /** [User] is banned from this room. */
// BAN_SUCCESS("ban_success"),
// /** This room is no longer in emote-only mode. */
// EMOTE_ONLY_OFF("emote_only_off"),
// /** This room is now in emote-only mode. */
// EMOTE_ONLY_ON("emote_only_on"),
// /** Exited host mode. */
// HOST_OFF("host_off"),
// /** Now hosting [Channel]. */
// HOST_ON("host_on"),
// /** There are [Number] host commands remaining this half hour. */
// HOST_REMAINING("hosts_remaining"),
// /** This channel is suspended. */
// MESSAGE_CHANNEL_SUSPENDED("msg_channel_suspended"),
// /**This room is no longer in r9k mode. */
// R9K_OFF("r9k_off"),
// /** This room is now in r9k mode. */
// R9K_ON("r9k_on"),
// /** This room is no longer in slow mode. */
// SLOW_OFF("slow_off"),
// /** This room is now in slow mode. You may send messages every [Seconds] seconds.*/
// SLOW_ON("slow_on"),
// /** This room is no longer in subscribers-only mode. */
// SUBSCRIBER_MODE_OFF("subs_off"),
// /** This room is now in subscribers-only mode. */
// SUBSCRIBER_MODE_ON("subs_on"),
// /** [User] has been timed out for [Seconds] seconds. */
// TIMEOUT_SUCCESS("timeout_success"),
// /** [User] is no longer banned from this chat room. */
// UNBAN_SUCCESS("unban_success"),
// /** Unrecognized command: [Command] */
// UNRECOGNIZED_COMMAND("unrecognized_cmd"),
//
// /**We default to this one if we do not recognize this NOTICE's event type. Since Twitch uses a lot of different undocumented
// * NOTICE types, there is need for a event type that works as a catch-all. <br>
// * Consider parsing the {@link Notice#getRawNoticeID()}.
// */
// OTHER("");
//
// private final String msgID;
// private NOTICE_EVENT(String msgID){
// this.msgID = msgID;
// }
//
// private final static Map<String, NOTICE_EVENT> mapping = new HashMap<>();
// static{
// for(NOTICE_EVENT n : values()){
// mapping.put(n.msgID, n);
// }
// }
//
// public static NOTICE_EVENT of(String msgID){
// return mapping.getOrDefault(msgID, OTHER);
// }
// };
// Path: src/test/java/com/gikk/twirk/types/notice/TestNotice.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.NOTICE_EVENT;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.notice;
public class TestNotice {
private final static String SUB_MODE_ON_MESSAGE = "@msg-id=subs_on :tmi.twitch.tv NOTICE #gikkman :This room is now in subscribers-only mode.";
private final static String SUB_MODE_OFF_MESSAGE = "@msg-id=subs_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in subscribers-only mode.";
private final static String R9K_MODE_ON_MESSAGE = "@msg-id=r9k_on :tmi.twitch.tv NOTICE #gikkman :This room is now in r9k mode.";
private final static String R9K_MODE_OFF_MESSAGE = "@msg-id=r9k_off :tmi.twitch.tv NOTICE #gikkman :This room is no longer in r9k mode.";
private final static String CUSTOM_MESSAGE = "@msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #gikkman :This ma' message now.";
public static void test(Consumer<String> twirkInput, TestConsumer<Notice> test ) throws Exception{ | TestResult res1 = test.assign(TestNotice::testSubModeOn); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/users/TwitchUserImpl.java | // Path: src/main/java/com/gikk/twirk/enums/USER_TYPE.java
// public enum USER_TYPE{
// /** Type for the owner of the channel (i.e. the user with the
// * same user name as the channel's name. This type has the highest value, 9*/
// OWNER(9),
//
// /** Type for mods in the channel. This type has the second highest value, 6 */
// MOD(6),
//
// /** Type for Twitch's global mods. This type has a value of 4*/
// GLOBAL_MOD(4),
//
// /** Type for Twitch's admins. This type has a value of 4*/
// ADMIN(4),
//
// /** Type for Twitch's staff members. This type has a value of 4*/
// STAFF(4),
//
// /** Type for channel subscribers. This type has a value of 2.
// * Note that both Turbo and Subs are given this type.
// * For more granularity, check out {@link TwitchUser#isSub()} and {@link TwitchUser#isMod()}
// */
// SUBSCRIBER(2),
//
// /** Type for users that does not fit into any other classes. This type has a value of 0*/
// DEFAULT(0);
//
// /** This type's value. Useful for regulating which kind of users should trigger / can perform
// * certain actions. <br><br>
// *
// * For example:<br>
// * <pre><code>if( user.USER_TYPE.value == USER_TYPE.MOD.value )</code>
// * <code>doSomething();</code></pre>
// */
// public final int value;
//
// private USER_TYPE(int value) {
// this.value = value;
// }
// }
| import com.gikk.twirk.enums.USER_TYPE; | package com.gikk.twirk.types.users;
class TwitchUserImpl implements TwitchUser{
//***********************************************************
// VARIABLES
//***********************************************************
private final String userName;
private final String displayName;
private final boolean isOwner;
private final boolean isMod;
private final boolean isSub;
private final boolean isTurbo;
private final int color;
private final long userID; | // Path: src/main/java/com/gikk/twirk/enums/USER_TYPE.java
// public enum USER_TYPE{
// /** Type for the owner of the channel (i.e. the user with the
// * same user name as the channel's name. This type has the highest value, 9*/
// OWNER(9),
//
// /** Type for mods in the channel. This type has the second highest value, 6 */
// MOD(6),
//
// /** Type for Twitch's global mods. This type has a value of 4*/
// GLOBAL_MOD(4),
//
// /** Type for Twitch's admins. This type has a value of 4*/
// ADMIN(4),
//
// /** Type for Twitch's staff members. This type has a value of 4*/
// STAFF(4),
//
// /** Type for channel subscribers. This type has a value of 2.
// * Note that both Turbo and Subs are given this type.
// * For more granularity, check out {@link TwitchUser#isSub()} and {@link TwitchUser#isMod()}
// */
// SUBSCRIBER(2),
//
// /** Type for users that does not fit into any other classes. This type has a value of 0*/
// DEFAULT(0);
//
// /** This type's value. Useful for regulating which kind of users should trigger / can perform
// * certain actions. <br><br>
// *
// * For example:<br>
// * <pre><code>if( user.USER_TYPE.value == USER_TYPE.MOD.value )</code>
// * <code>doSomething();</code></pre>
// */
// public final int value;
//
// private USER_TYPE(int value) {
// this.value = value;
// }
// }
// Path: src/main/java/com/gikk/twirk/types/users/TwitchUserImpl.java
import com.gikk.twirk.enums.USER_TYPE;
package com.gikk.twirk.types.users;
class TwitchUserImpl implements TwitchUser{
//***********************************************************
// VARIABLES
//***********************************************************
private final String userName;
private final String displayName;
private final boolean isOwner;
private final boolean isMod;
private final boolean isSub;
private final boolean isTurbo;
private final int color;
private final long userID; | private final USER_TYPE userType; |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/usernotice/SubscriptionImpl.java | // Path: src/main/java/com/gikk/twirk/types/usernotice/subtype/Subscription.java
// public interface Subscription {
// public SubscriptionPlan getSubscriptionPlan();
//
// /**Get the number of month's the subscription's been active. New subscriptions
// * return 1, whilst re-subscriptions tells which month was just activated.
// *
// * @return number of months
// */
// public int getMonths();
//
// /**Get the number of month's the subscription's been active consecutive.
// *
// * @return number of months
// */
// public int getStreak();
//
// /** Returns if user decide to share the streak, this decide if the value of {@code getStreak} its zero or another.
// *
// * @return {@code true} if user share the streak
// */
// public boolean isSharedStreak();
//
// /**Returns the name of the purchased subscription plan. This may be a
// * default name or one created by the channel owner.
// *
// * @return display name of the subscription plan
// */
// public String getSubscriptionPlanName();
//
// /**Returns whether this was a new sub or a re-sub.
// *
// * @return {@code true} if this was a re-subscription
// */
// public boolean isResub();
//
// /**Tells whether this is a subscription gift or not.
// *
// * @return {@code true} if this was a gift
// */
// public boolean isGift();
//
// /**Retrieves the SubscriptionGift item, which holds information about the
// * gift and the recipiant of the gift. The Optional object wraps the
// * SubscriptionGift object (as an alternative to returning {@code null}).
// *
// * @return the subscription gift, wrapped in a {@link Optional}
// */
// public Optional<SubscriptionGift> getSubscriptionGift();
// }
//
// Path: src/main/java/com/gikk/twirk/types/usernotice/subtype/SubscriptionGift.java
// public interface SubscriptionGift {
// /**
// * Fetches the recipients display name (as configured by the user).
// * @return the display name
// */
// public String getRecipiantDisplayName();
//
// /**
// * Fetches the recipients user name (i.e. their login name).
// * @return the user name
// */
// public String getRecipiantUserName();
//
// /**
// *Fetches the recipients user ID
// * @return the user ID
// */
// public long getRecipiantUserID();
// }
//
// Path: src/main/java/com/gikk/twirk/types/usernotice/subtype/SubscriptionPlan.java
// public enum SubscriptionPlan {
// /** Subscribed with Twitch Prime
// */
// SUB_PRIME("Prime", "Prime"),
//
// /** Subscribed with a 4.99$ plan
// */
// SUB_LOW("1000", "4.99$"),
//
// /** Subscribed with a 9.99$ plan
// */
// SUB_MID("2000", "9.99$"),
//
// /** Subscribed with a 24.99$ plan
// */
// SUB_HIGH("3000", "24.99$");
//
// private final String message;
// private final String value;
// private SubscriptionPlan(String msg, String val){
// this.message = msg;
// this.value = val;
// }
//
// public String getValue(){
// return value;
// }
//
// /**Attempts to parse which Subscription plan that's been used, given the
// * subscription notice message.
// * <p>
// * If no match is found (i.e. the input parameter is unknown) this defaults
// * to returning {@link SubscriptionPlan#SUB_LOW}
// *
// * @param paramSubPlan the sub-plan message
// * @return a SubscriptionPlan
// */
// public static SubscriptionPlan of(String paramSubPlan){
// for(SubscriptionPlan s : values()){
// if(s.message.equals(paramSubPlan)) {
// return s;
// }
// }
// return SUB_LOW;
// }
// }
| import com.gikk.twirk.types.usernotice.subtype.Subscription;
import com.gikk.twirk.types.usernotice.subtype.SubscriptionGift;
import com.gikk.twirk.types.usernotice.subtype.SubscriptionPlan;
import java.util.Optional; | package com.gikk.twirk.types.usernotice;
/**
*
* @author Gikkman
*/
class SubscriptionImpl implements Subscription {
private final SubscriptionPlan plan;
private final int months;
private final int streak;
private final boolean shareStreak;
private final String planName; | // Path: src/main/java/com/gikk/twirk/types/usernotice/subtype/Subscription.java
// public interface Subscription {
// public SubscriptionPlan getSubscriptionPlan();
//
// /**Get the number of month's the subscription's been active. New subscriptions
// * return 1, whilst re-subscriptions tells which month was just activated.
// *
// * @return number of months
// */
// public int getMonths();
//
// /**Get the number of month's the subscription's been active consecutive.
// *
// * @return number of months
// */
// public int getStreak();
//
// /** Returns if user decide to share the streak, this decide if the value of {@code getStreak} its zero or another.
// *
// * @return {@code true} if user share the streak
// */
// public boolean isSharedStreak();
//
// /**Returns the name of the purchased subscription plan. This may be a
// * default name or one created by the channel owner.
// *
// * @return display name of the subscription plan
// */
// public String getSubscriptionPlanName();
//
// /**Returns whether this was a new sub or a re-sub.
// *
// * @return {@code true} if this was a re-subscription
// */
// public boolean isResub();
//
// /**Tells whether this is a subscription gift or not.
// *
// * @return {@code true} if this was a gift
// */
// public boolean isGift();
//
// /**Retrieves the SubscriptionGift item, which holds information about the
// * gift and the recipiant of the gift. The Optional object wraps the
// * SubscriptionGift object (as an alternative to returning {@code null}).
// *
// * @return the subscription gift, wrapped in a {@link Optional}
// */
// public Optional<SubscriptionGift> getSubscriptionGift();
// }
//
// Path: src/main/java/com/gikk/twirk/types/usernotice/subtype/SubscriptionGift.java
// public interface SubscriptionGift {
// /**
// * Fetches the recipients display name (as configured by the user).
// * @return the display name
// */
// public String getRecipiantDisplayName();
//
// /**
// * Fetches the recipients user name (i.e. their login name).
// * @return the user name
// */
// public String getRecipiantUserName();
//
// /**
// *Fetches the recipients user ID
// * @return the user ID
// */
// public long getRecipiantUserID();
// }
//
// Path: src/main/java/com/gikk/twirk/types/usernotice/subtype/SubscriptionPlan.java
// public enum SubscriptionPlan {
// /** Subscribed with Twitch Prime
// */
// SUB_PRIME("Prime", "Prime"),
//
// /** Subscribed with a 4.99$ plan
// */
// SUB_LOW("1000", "4.99$"),
//
// /** Subscribed with a 9.99$ plan
// */
// SUB_MID("2000", "9.99$"),
//
// /** Subscribed with a 24.99$ plan
// */
// SUB_HIGH("3000", "24.99$");
//
// private final String message;
// private final String value;
// private SubscriptionPlan(String msg, String val){
// this.message = msg;
// this.value = val;
// }
//
// public String getValue(){
// return value;
// }
//
// /**Attempts to parse which Subscription plan that's been used, given the
// * subscription notice message.
// * <p>
// * If no match is found (i.e. the input parameter is unknown) this defaults
// * to returning {@link SubscriptionPlan#SUB_LOW}
// *
// * @param paramSubPlan the sub-plan message
// * @return a SubscriptionPlan
// */
// public static SubscriptionPlan of(String paramSubPlan){
// for(SubscriptionPlan s : values()){
// if(s.message.equals(paramSubPlan)) {
// return s;
// }
// }
// return SUB_LOW;
// }
// }
// Path: src/main/java/com/gikk/twirk/types/usernotice/SubscriptionImpl.java
import com.gikk.twirk.types.usernotice.subtype.Subscription;
import com.gikk.twirk.types.usernotice.subtype.SubscriptionGift;
import com.gikk.twirk.types.usernotice.subtype.SubscriptionPlan;
import java.util.Optional;
package com.gikk.twirk.types.usernotice;
/**
*
* @author Gikkman
*/
class SubscriptionImpl implements Subscription {
private final SubscriptionPlan plan;
private final int months;
private final int streak;
private final boolean shareStreak;
private final String planName; | private final Optional<SubscriptionGift> subGift; |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/users/UserstateBuilder.java | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
| import com.gikk.twirk.types.twitchMessage.TwitchMessage; | package com.gikk.twirk.types.users;
/**Constructs a {@link Userstate} object. To create a {@link Userstate} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface UserstateBuilder {
public static UserstateBuilder getDefault() {
return new DefaultUserstateBuilder();
}
/**Constructs a new {@link Userstate} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Userstate} object.
* Make sure that the COMMAND equals "USERSTATE"
*
* @param message The message we received from Twitch
* @return A {@link Userstate}, or <code>null</code> if a {@link Userstate} could not be created
*/ | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
// Path: src/main/java/com/gikk/twirk/types/users/UserstateBuilder.java
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
package com.gikk.twirk.types.users;
/**Constructs a {@link Userstate} object. To create a {@link Userstate} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface UserstateBuilder {
public static UserstateBuilder getDefault() {
return new DefaultUserstateBuilder();
}
/**Constructs a new {@link Userstate} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Userstate} object.
* Make sure that the COMMAND equals "USERSTATE"
*
* @param message The message we received from Twitch
* @return A {@link Userstate}, or <code>null</code> if a {@link Userstate} could not be created
*/ | public Userstate build(TwitchMessage message); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/emote/TestEmote.java | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
//
// Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessageBuilder.java
// public interface TwitchMessageBuilder {
//
// /**Constructs a new {@link TwitchMessage} object from a chat line received from Twitch.<br>
// * A valid chat line has 2-5 segments:<br>
// * <code>@TAG<optional> :PREFIX COMMAND TARGET<optional> :CONTENT<optional></code>
// * <br><br>
// * From this chat line, we create a {@link TwitchMessage}. If certain parts are not present, the corresponding
// * <code>get</code> method on the {@link TwitchMessage} will return an empty string.
// *
// * @param chatLine The chat line, <b>exactly</b> as received from Twitch
// * @return A {@link TwitchMessage}, or <code>null</code> if a {@link TwitchMessage} could not be created
// */
// public TwitchMessage build(String chatLine);
//
// static TwitchMessageBuilder getDefault(){
// return new DefaultTwitchMessageBuilder();
// }
// }
| import com.gikk.twirk.types.twitchMessage.TwitchMessage;
import com.gikk.twirk.types.twitchMessage.TwitchMessageBuilder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*; | package com.gikk.twirk.types.emote;
/**
*
* @author Gikkman
*/
public class TestEmote {
@Test
public void noEmotesTest_whenNoEmotesNodeInTag_thenParsesNoEmotes(){
// Given
String input = "@badges=;color=;display-name=Gikkman;mod=0;room-id=1;subscriber=0;turbo=0;user-id=1;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage";
// When | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
//
// Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessageBuilder.java
// public interface TwitchMessageBuilder {
//
// /**Constructs a new {@link TwitchMessage} object from a chat line received from Twitch.<br>
// * A valid chat line has 2-5 segments:<br>
// * <code>@TAG<optional> :PREFIX COMMAND TARGET<optional> :CONTENT<optional></code>
// * <br><br>
// * From this chat line, we create a {@link TwitchMessage}. If certain parts are not present, the corresponding
// * <code>get</code> method on the {@link TwitchMessage} will return an empty string.
// *
// * @param chatLine The chat line, <b>exactly</b> as received from Twitch
// * @return A {@link TwitchMessage}, or <code>null</code> if a {@link TwitchMessage} could not be created
// */
// public TwitchMessage build(String chatLine);
//
// static TwitchMessageBuilder getDefault(){
// return new DefaultTwitchMessageBuilder();
// }
// }
// Path: src/test/java/com/gikk/twirk/types/emote/TestEmote.java
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
import com.gikk.twirk.types.twitchMessage.TwitchMessageBuilder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
package com.gikk.twirk.types.emote;
/**
*
* @author Gikkman
*/
public class TestEmote {
@Test
public void noEmotesTest_whenNoEmotesNodeInTag_thenParsesNoEmotes(){
// Given
String input = "@badges=;color=;display-name=Gikkman;mod=0;room-id=1;subscriber=0;turbo=0;user-id=1;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage";
// When | TwitchMessage message = TwitchMessageBuilder.getDefault().build(input); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/emote/TestEmote.java | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
//
// Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessageBuilder.java
// public interface TwitchMessageBuilder {
//
// /**Constructs a new {@link TwitchMessage} object from a chat line received from Twitch.<br>
// * A valid chat line has 2-5 segments:<br>
// * <code>@TAG<optional> :PREFIX COMMAND TARGET<optional> :CONTENT<optional></code>
// * <br><br>
// * From this chat line, we create a {@link TwitchMessage}. If certain parts are not present, the corresponding
// * <code>get</code> method on the {@link TwitchMessage} will return an empty string.
// *
// * @param chatLine The chat line, <b>exactly</b> as received from Twitch
// * @return A {@link TwitchMessage}, or <code>null</code> if a {@link TwitchMessage} could not be created
// */
// public TwitchMessage build(String chatLine);
//
// static TwitchMessageBuilder getDefault(){
// return new DefaultTwitchMessageBuilder();
// }
// }
| import com.gikk.twirk.types.twitchMessage.TwitchMessage;
import com.gikk.twirk.types.twitchMessage.TwitchMessageBuilder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*; | package com.gikk.twirk.types.emote;
/**
*
* @author Gikkman
*/
public class TestEmote {
@Test
public void noEmotesTest_whenNoEmotesNodeInTag_thenParsesNoEmotes(){
// Given
String input = "@badges=;color=;display-name=Gikkman;mod=0;room-id=1;subscriber=0;turbo=0;user-id=1;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage";
// When | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
//
// Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessageBuilder.java
// public interface TwitchMessageBuilder {
//
// /**Constructs a new {@link TwitchMessage} object from a chat line received from Twitch.<br>
// * A valid chat line has 2-5 segments:<br>
// * <code>@TAG<optional> :PREFIX COMMAND TARGET<optional> :CONTENT<optional></code>
// * <br><br>
// * From this chat line, we create a {@link TwitchMessage}. If certain parts are not present, the corresponding
// * <code>get</code> method on the {@link TwitchMessage} will return an empty string.
// *
// * @param chatLine The chat line, <b>exactly</b> as received from Twitch
// * @return A {@link TwitchMessage}, or <code>null</code> if a {@link TwitchMessage} could not be created
// */
// public TwitchMessage build(String chatLine);
//
// static TwitchMessageBuilder getDefault(){
// return new DefaultTwitchMessageBuilder();
// }
// }
// Path: src/test/java/com/gikk/twirk/types/emote/TestEmote.java
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
import com.gikk.twirk.types.twitchMessage.TwitchMessageBuilder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
package com.gikk.twirk.types.emote;
/**
*
* @author Gikkman
*/
public class TestEmote {
@Test
public void noEmotesTest_whenNoEmotesNodeInTag_thenParsesNoEmotes(){
// Given
String input = "@badges=;color=;display-name=Gikkman;mod=0;room-id=1;subscriber=0;turbo=0;user-id=1;user-type= :gikkman!gikkman@gikkman.tmi.twitch.tv PRIVMSG #gikkman :userMessage";
// When | TwitchMessage message = TwitchMessageBuilder.getDefault().build(input); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/users/Userstate.java | // Path: src/main/java/com/gikk/twirk/enums/USER_TYPE.java
// public enum USER_TYPE{
// /** Type for the owner of the channel (i.e. the user with the
// * same user name as the channel's name. This type has the highest value, 9*/
// OWNER(9),
//
// /** Type for mods in the channel. This type has the second highest value, 6 */
// MOD(6),
//
// /** Type for Twitch's global mods. This type has a value of 4*/
// GLOBAL_MOD(4),
//
// /** Type for Twitch's admins. This type has a value of 4*/
// ADMIN(4),
//
// /** Type for Twitch's staff members. This type has a value of 4*/
// STAFF(4),
//
// /** Type for channel subscribers. This type has a value of 2.
// * Note that both Turbo and Subs are given this type.
// * For more granularity, check out {@link TwitchUser#isSub()} and {@link TwitchUser#isMod()}
// */
// SUBSCRIBER(2),
//
// /** Type for users that does not fit into any other classes. This type has a value of 0*/
// DEFAULT(0);
//
// /** This type's value. Useful for regulating which kind of users should trigger / can perform
// * certain actions. <br><br>
// *
// * For example:<br>
// * <pre><code>if( user.USER_TYPE.value == USER_TYPE.MOD.value )</code>
// * <code>doSomething();</code></pre>
// */
// public final int value;
//
// private USER_TYPE(int value) {
// this.value = value;
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/AbstractType.java
// public interface AbstractType {
// /**Get the raw chat line, which this type was constructed from
// *
// * @return The raw chat line, just as seen from the server
// */
// public String getRaw();
// }
| import com.gikk.twirk.enums.USER_TYPE;
import com.gikk.twirk.types.AbstractType; | package com.gikk.twirk.types.users;
/**Class for representing a CLEARCHAT from Twitch.<br><br>
*
* Twitch sends us USERSTATE as a response whenever we send them a message. The USERSTATE message will tell
* us certain properties related to ourselves, such as our display name, our color, if we're mod and so on. Objects
* of this class can thus be used to inspect what properties we have on Twitch's side.<br><br>
*
* For documentation about how Twitch communicates via IRC,
* see <a href="https://github.com/justintv/Twitch-API/blob/master/IRC.md">
* https://github.com/justintv/Twitch-API/blob/master/IRC.md </a>
*
* @author Gikkman
*
*/
public interface Userstate extends AbstractType{
/**Retrieves our display color, as a hex-number. <br>
* If we have no color set on Twitch's side, a semi-random color will be generated
*
* @return Our display color
*/
public int getColor();
/**Retrieves our display name, as seen in chat on Twitch
*
* @return Our display name
*/
public String getDisplayName();
/**Retrieves information on whether we are a mod in this channel or not.
*
* @return <code>true</code> if we are mod
*/
public boolean isMod();
/**Retrieves information on whether we are a sub in this channel or not.
*
* @return <code>true</code> if we are sub
*/
public boolean isSub();
/**Retrieves information on whether we have Turbo, or not
*
* @return <code>true</code> if we have turbo
*/
public boolean isTurbo();
/**Retrieves information on what type of user we are in this channel. See {@link USER_TYPE}
*
* @return Our {@link USER_TYPE}
*/ | // Path: src/main/java/com/gikk/twirk/enums/USER_TYPE.java
// public enum USER_TYPE{
// /** Type for the owner of the channel (i.e. the user with the
// * same user name as the channel's name. This type has the highest value, 9*/
// OWNER(9),
//
// /** Type for mods in the channel. This type has the second highest value, 6 */
// MOD(6),
//
// /** Type for Twitch's global mods. This type has a value of 4*/
// GLOBAL_MOD(4),
//
// /** Type for Twitch's admins. This type has a value of 4*/
// ADMIN(4),
//
// /** Type for Twitch's staff members. This type has a value of 4*/
// STAFF(4),
//
// /** Type for channel subscribers. This type has a value of 2.
// * Note that both Turbo and Subs are given this type.
// * For more granularity, check out {@link TwitchUser#isSub()} and {@link TwitchUser#isMod()}
// */
// SUBSCRIBER(2),
//
// /** Type for users that does not fit into any other classes. This type has a value of 0*/
// DEFAULT(0);
//
// /** This type's value. Useful for regulating which kind of users should trigger / can perform
// * certain actions. <br><br>
// *
// * For example:<br>
// * <pre><code>if( user.USER_TYPE.value == USER_TYPE.MOD.value )</code>
// * <code>doSomething();</code></pre>
// */
// public final int value;
//
// private USER_TYPE(int value) {
// this.value = value;
// }
// }
//
// Path: src/main/java/com/gikk/twirk/types/AbstractType.java
// public interface AbstractType {
// /**Get the raw chat line, which this type was constructed from
// *
// * @return The raw chat line, just as seen from the server
// */
// public String getRaw();
// }
// Path: src/main/java/com/gikk/twirk/types/users/Userstate.java
import com.gikk.twirk.enums.USER_TYPE;
import com.gikk.twirk.types.AbstractType;
package com.gikk.twirk.types.users;
/**Class for representing a CLEARCHAT from Twitch.<br><br>
*
* Twitch sends us USERSTATE as a response whenever we send them a message. The USERSTATE message will tell
* us certain properties related to ourselves, such as our display name, our color, if we're mod and so on. Objects
* of this class can thus be used to inspect what properties we have on Twitch's side.<br><br>
*
* For documentation about how Twitch communicates via IRC,
* see <a href="https://github.com/justintv/Twitch-API/blob/master/IRC.md">
* https://github.com/justintv/Twitch-API/blob/master/IRC.md </a>
*
* @author Gikkman
*
*/
public interface Userstate extends AbstractType{
/**Retrieves our display color, as a hex-number. <br>
* If we have no color set on Twitch's side, a semi-random color will be generated
*
* @return Our display color
*/
public int getColor();
/**Retrieves our display name, as seen in chat on Twitch
*
* @return Our display name
*/
public String getDisplayName();
/**Retrieves information on whether we are a mod in this channel or not.
*
* @return <code>true</code> if we are mod
*/
public boolean isMod();
/**Retrieves information on whether we are a sub in this channel or not.
*
* @return <code>true</code> if we are sub
*/
public boolean isSub();
/**Retrieves information on whether we have Turbo, or not
*
* @return <code>true</code> if we have turbo
*/
public boolean isTurbo();
/**Retrieves information on what type of user we are in this channel. See {@link USER_TYPE}
*
* @return Our {@link USER_TYPE}
*/ | public USER_TYPE getUserType(); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/mode/ModeBuilder.java | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
| import com.gikk.twirk.types.twitchMessage.TwitchMessage; | package com.gikk.twirk.types.mode;
/**Constructs a {@link Mode} object. To create a {@link Mode} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface ModeBuilder {
public static ModeBuilder getDefault() {
return new DefaultModeBuilder();
}
/**Constructs a new {@link Mode} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Mode} object.
* Make sure that the COMMAND of the message equals "MODE"
*
* @param message The message we received from Twitch
* @return A {@link Mode}, or <code>null</code> if a {@link Mode} could not be created
*/ | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
// Path: src/main/java/com/gikk/twirk/types/mode/ModeBuilder.java
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
package com.gikk.twirk.types.mode;
/**Constructs a {@link Mode} object. To create a {@link Mode} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface ModeBuilder {
public static ModeBuilder getDefault() {
return new DefaultModeBuilder();
}
/**Constructs a new {@link Mode} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Mode} object.
* Make sure that the COMMAND of the message equals "MODE"
*
* @param message The message we received from Twitch
* @return A {@link Mode}, or <code>null</code> if a {@link Mode} could not be created
*/ | public Mode build(TwitchMessage message); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/TestNamelist.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Consumer;
import org.junit.Assert; | package com.gikk.twirk.types;
/**
*
* @author Gikkman
*/
public class TestNamelist {
public static void test(Consumer<String> twirkIn, | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
// Path: src/test/java/com/gikk/twirk/types/TestNamelist.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Consumer;
import org.junit.Assert;
package com.gikk.twirk.types;
/**
*
* @author Gikkman
*/
public class TestNamelist {
public static void test(Consumer<String> twirkIn, | TestConsumer<Collection<String>> test) throws Exception{ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/TestNamelist.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Consumer;
import org.junit.Assert; | package com.gikk.twirk.types;
/**
*
* @author Gikkman
*/
public class TestNamelist {
public static void test(Consumer<String> twirkIn,
TestConsumer<Collection<String>> test) throws Exception{ | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
// Path: src/test/java/com/gikk/twirk/types/TestNamelist.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Consumer;
import org.junit.Assert;
package com.gikk.twirk.types;
/**
*
* @author Gikkman
*/
public class TestNamelist {
public static void test(Consumer<String> twirkIn,
TestConsumer<Collection<String>> test) throws Exception{ | TestResult res = test.assign( (list) -> { |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/notice/NoticeBuilder.java | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
| import com.gikk.twirk.types.twitchMessage.TwitchMessage; | package com.gikk.twirk.types.notice;
/**Constructs a {@link Notice} object. To create a {@link Notice} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface NoticeBuilder {
public static NoticeBuilder getDefault() {
return new DefaultNoticeBuilder();
}
/**Constructs a new {@link Notice} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Notice} object.
* Make sure that the COMMAND of the message equals "NOTICE"
*
* @param message The message we received from Twitch
* @return A {@link Notice}, or <code>null</code> if a {@link Notice} could not be created
*/ | // Path: src/main/java/com/gikk/twirk/types/twitchMessage/TwitchMessage.java
// public interface TwitchMessage extends AbstractEmoteMessage {
//
// /**Retrieves this message's tag segment. Should always starts with a @. Note that the
// * Tag segment will look vastly different for different Twitch commands, and some won't
// * even have a tag.
// *
// * @return The tag segment, or {@code ""} if no tag was present
// */
// public String getTag();
//
// /**Retrieves the message's prefix.<br><br>
// *
// * A typical Twitch message looks something line this:<br>
// * <code>:name!name@name.tmi.twitch.tv COMMAND #channel :message</code> <br><br>
// *
// * The prefix is the part before the first space. It usually only contains data about the sender of
// * the message, but it might sometimes contain other information (PING messages for example just have PING as
// * their prefix).<br><br>
// *
// * @return The messages prefix
// */
// public String getPrefix();
//
// /**Retrieves the message's command.<br>
// * The command tells us what action triggered this message being sent.<br><br>
// *
// * @return The message's command
// */
// public String getCommand();
//
// /**Retrieves the message's target.<br>
// * The target tells us whom the message is intended towards. It can be a user,
// * a channel, or something else (though mostly the channel).
// * <p>
// * This segment is not always present.
// *
// * @return The message's target, or {@code ""} if no target
// */
// public String getTarget();
//
// /**Retrieves the message's content.<br>
// * The content is the commands parameters. Most often, this is the actual chat message, but it may be many
// * other things for other commands.<br><br>
// *
// * This segment is not always present.
// *
// * @return The message's content, or {@code ""} if no content
// */
// public String getContent();
//
// /**Tells whether this message was a cheer event or not.
// *
// * @return {@code true} if the message contains bits, <code>false</code> otherwise
// */
// public boolean isCheer();
//
// /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.
// * The list might be empty, if the message contained no cheers.
// *
// * @return List of emotes (might be empty)
// */
// public List<Cheer> getCheers();
//
// /**Fetches the total number of bits that this message contained.
// * This method is short-hand for:
// * <pre>
// * int bits = 0;
// * for(Cheer c : getCheers())
// * bits += c.getBits();
// * return bits;
// * </pre>
// * @return number of bits
// */
// public int getBits();
//
// /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.
// * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.
// */
// public TagMap getTagMap();
// }
// Path: src/main/java/com/gikk/twirk/types/notice/NoticeBuilder.java
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
package com.gikk.twirk.types.notice;
/**Constructs a {@link Notice} object. To create a {@link Notice} object, call the {@link #build(TwitchMessage)} method
*
* @author Gikkman
*
*/
public interface NoticeBuilder {
public static NoticeBuilder getDefault() {
return new DefaultNoticeBuilder();
}
/**Constructs a new {@link Notice} object from a {@link TwitchMessage}, received from Twitch. The user
* is responsible for making sure that this message can actually be made into a {@link Notice} object.
* Make sure that the COMMAND of the message equals "NOTICE"
*
* @param message The message we received from Twitch
* @return A {@link Notice}, or <code>null</code> if a {@link Notice} could not be created
*/ | public Notice build(TwitchMessage message); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/clearChat/TestClearChat.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/CLEARCHAT_MODE.java
// public enum CLEARCHAT_MODE{
// /** A user has been purged/banned
// */
// USER,
//
// /** The entire chat has been pruged
// */
// COMPLETE };
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.CLEARCHAT_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.clearChat;
public class TestClearChat {
private static final String COMPLETE = ":tmi.twitch.tv CLEARCHAT #gikkman";
private static final String DURATION_NO_REASON = "@ban-duration=20;ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_NO_REASON = "@ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String DURATION_REASON = "@ban-duration=10;ban-reason=Bad :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_REASON = "@ban-reason=Bad\\sargument :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
| // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/CLEARCHAT_MODE.java
// public enum CLEARCHAT_MODE{
// /** A user has been purged/banned
// */
// USER,
//
// /** The entire chat has been pruged
// */
// COMPLETE };
// Path: src/test/java/com/gikk/twirk/types/clearChat/TestClearChat.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.CLEARCHAT_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.clearChat;
public class TestClearChat {
private static final String COMPLETE = ":tmi.twitch.tv CLEARCHAT #gikkman";
private static final String DURATION_NO_REASON = "@ban-duration=20;ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_NO_REASON = "@ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String DURATION_REASON = "@ban-duration=10;ban-reason=Bad :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_REASON = "@ban-reason=Bad\\sargument :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
| public static void test(Consumer<String> twirkInput, TestConsumer<ClearChat> test ) throws Exception{ |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/clearChat/TestClearChat.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/CLEARCHAT_MODE.java
// public enum CLEARCHAT_MODE{
// /** A user has been purged/banned
// */
// USER,
//
// /** The entire chat has been pruged
// */
// COMPLETE };
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.CLEARCHAT_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.clearChat;
public class TestClearChat {
private static final String COMPLETE = ":tmi.twitch.tv CLEARCHAT #gikkman";
private static final String DURATION_NO_REASON = "@ban-duration=20;ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_NO_REASON = "@ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String DURATION_REASON = "@ban-duration=10;ban-reason=Bad :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_REASON = "@ban-reason=Bad\\sargument :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
public static void test(Consumer<String> twirkInput, TestConsumer<ClearChat> test ) throws Exception{ | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/CLEARCHAT_MODE.java
// public enum CLEARCHAT_MODE{
// /** A user has been purged/banned
// */
// USER,
//
// /** The entire chat has been pruged
// */
// COMPLETE };
// Path: src/test/java/com/gikk/twirk/types/clearChat/TestClearChat.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.CLEARCHAT_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.clearChat;
public class TestClearChat {
private static final String COMPLETE = ":tmi.twitch.tv CLEARCHAT #gikkman";
private static final String DURATION_NO_REASON = "@ban-duration=20;ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_NO_REASON = "@ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String DURATION_REASON = "@ban-duration=10;ban-reason=Bad :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_REASON = "@ban-reason=Bad\\sargument :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
public static void test(Consumer<String> twirkInput, TestConsumer<ClearChat> test ) throws Exception{ | TestResult resComplete = test.assign(TestClearChat::testComplete); |
Gikkman/Java-Twirk | src/test/java/com/gikk/twirk/types/clearChat/TestClearChat.java | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/CLEARCHAT_MODE.java
// public enum CLEARCHAT_MODE{
// /** A user has been purged/banned
// */
// USER,
//
// /** The entire chat has been pruged
// */
// COMPLETE };
| import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.CLEARCHAT_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*; | package com.gikk.twirk.types.clearChat;
public class TestClearChat {
private static final String COMPLETE = ":tmi.twitch.tv CLEARCHAT #gikkman";
private static final String DURATION_NO_REASON = "@ban-duration=20;ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_NO_REASON = "@ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String DURATION_REASON = "@ban-duration=10;ban-reason=Bad :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_REASON = "@ban-reason=Bad\\sargument :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
public static void test(Consumer<String> twirkInput, TestConsumer<ClearChat> test ) throws Exception{
TestResult resComplete = test.assign(TestClearChat::testComplete);
twirkInput.accept(COMPLETE);
resComplete.await();
TestResult resDNR = test.assign(TestClearChat::testDurationNoReason);
twirkInput.accept(DURATION_NO_REASON);
resDNR.await();
TestResult resNDNR = test.assign(TestClearChat::testNoDurationNoReason);
twirkInput.accept(NO_DURATION_NO_REASON);
resNDNR.await();
TestResult resDR = test.assign(TestClearChat::testDurationReason);
twirkInput.accept(DURATION_REASON);
resDR.await();
TestResult resNDR = test.assign(TestClearChat::testNoDurationReason);
twirkInput.accept(NO_DURATION_REASON);
resNDR.await();
}
static boolean testComplete(ClearChat c){ | // Path: src/test/java/com/gikk/twirk/TestConsumer.java
// public class TestConsumer<T> {
// private Function<T, Boolean> test;
// private TestResult res;
//
// public TestResult assign(Function<T, Boolean> test){
// this.test = test;
// return res = new TestResult();
// }
//
// public void consume(T input){
// if(test != null) {
// res.complete(test.apply(input));
// }
// }
// }
//
// Path: src/test/java/com/gikk/twirk/TestResult.java
// public class TestResult {
// CompletableFuture<Boolean> res = new CompletableFuture<>();
//
// TestResult(){ }
//
// void complete(boolean result){
// res.complete(result);
// }
//
// public boolean await() throws Exception {
// return res.get(TestSuit.WAIT_TIME, TestSuit.UNIT);
// }
// }
//
// Path: src/main/java/com/gikk/twirk/enums/CLEARCHAT_MODE.java
// public enum CLEARCHAT_MODE{
// /** A user has been purged/banned
// */
// USER,
//
// /** The entire chat has been pruged
// */
// COMPLETE };
// Path: src/test/java/com/gikk/twirk/types/clearChat/TestClearChat.java
import com.gikk.twirk.TestConsumer;
import com.gikk.twirk.TestResult;
import com.gikk.twirk.enums.CLEARCHAT_MODE;
import java.util.function.Consumer;
import static org.junit.Assert.*;
package com.gikk.twirk.types.clearChat;
public class TestClearChat {
private static final String COMPLETE = ":tmi.twitch.tv CLEARCHAT #gikkman";
private static final String DURATION_NO_REASON = "@ban-duration=20;ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_NO_REASON = "@ban-reason= :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String DURATION_REASON = "@ban-duration=10;ban-reason=Bad :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
private static final String NO_DURATION_REASON = "@ban-reason=Bad\\sargument :tmi.twitch.tv CLEARCHAT #gikkman :gikkbot";
public static void test(Consumer<String> twirkInput, TestConsumer<ClearChat> test ) throws Exception{
TestResult resComplete = test.assign(TestClearChat::testComplete);
twirkInput.accept(COMPLETE);
resComplete.await();
TestResult resDNR = test.assign(TestClearChat::testDurationNoReason);
twirkInput.accept(DURATION_NO_REASON);
resDNR.await();
TestResult resNDNR = test.assign(TestClearChat::testNoDurationNoReason);
twirkInput.accept(NO_DURATION_NO_REASON);
resNDNR.await();
TestResult resDR = test.assign(TestClearChat::testDurationReason);
twirkInput.accept(DURATION_REASON);
resDR.await();
TestResult resNDR = test.assign(TestClearChat::testNoDurationReason);
twirkInput.accept(NO_DURATION_REASON);
resNDR.await();
}
static boolean testComplete(ClearChat c){ | test(c, CLEARCHAT_MODE.COMPLETE, "", -1, ""); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/emote/Emote.java | // Path: src/main/java/com/gikk/twirk/enums/EMOTE_SIZE.java
// public enum EMOTE_SIZE{
// SMALL("/1.0"),
// MEDIUM("/2.0"),
// LARGE("/3.0");
// public final String value;
// private EMOTE_SIZE(String val){ this.value = val; }
// }
| import java.util.LinkedList;
import com.gikk.twirk.enums.EMOTE_SIZE; | package com.gikk.twirk.types.emote;
/**Class for representing a Twitch emote, which can be embedded into chat messages.<br><br>
*
* An emote has three features: <ul>
* <li>EmoteID - The numeric ID for the emote.
* <li>Pattern - The emote's string pattern (Ex. 'Kappa')
* <li>Indices - For each time an emote is present in a message, the emotes begin- and end index must be listed. Begin is inclusive, end is exclusive
* </ul>
* For example, if the message is: {@code Kappa PogChamp Kappa}<br> the TwirkEmote for Kappa will be:<ul>
* <li>EmoteID = 25
* <li>Pattern = Kappa
* <li>Indices = (0,5), (15,20)
*
* @author Gikkman
*
*/
public interface Emote {
/** Fetches the emotes ID as String. This became necessary after Twitch start
* including other characters than numbers in emote IDs
*
* @return The emotes ID
*/
String getEmoteIDString();
/** A list of pairs on indices. Each pair is a BEGIN-END pair of a emote occurrence in the message.<br><br>
*
* For example, if the message is: {@code Kappa PogChamp Kappa}<br> the list for emote 'Kappa' will include these pairs:<ul>
* <li> (0,5)
* <li> (15,20)
* </ul>
*
* @return The indices this emote takes up in the associated message
*/
LinkedList<EmoteIndices> getIndices();
/** The emote's pattern. For example: 'Kappa'
*
* @return The emote's pattern
*/
String getPattern();
/**Emote images can be downloaded from Twitch's server, and come in three
* sizes. Use this method to get the address for the emote.
*
* @param imageSize Emotes comes in three sizes. Specify which size you want
* @return The address for the emote's image
*/ | // Path: src/main/java/com/gikk/twirk/enums/EMOTE_SIZE.java
// public enum EMOTE_SIZE{
// SMALL("/1.0"),
// MEDIUM("/2.0"),
// LARGE("/3.0");
// public final String value;
// private EMOTE_SIZE(String val){ this.value = val; }
// }
// Path: src/main/java/com/gikk/twirk/types/emote/Emote.java
import java.util.LinkedList;
import com.gikk.twirk.enums.EMOTE_SIZE;
package com.gikk.twirk.types.emote;
/**Class for representing a Twitch emote, which can be embedded into chat messages.<br><br>
*
* An emote has three features: <ul>
* <li>EmoteID - The numeric ID for the emote.
* <li>Pattern - The emote's string pattern (Ex. 'Kappa')
* <li>Indices - For each time an emote is present in a message, the emotes begin- and end index must be listed. Begin is inclusive, end is exclusive
* </ul>
* For example, if the message is: {@code Kappa PogChamp Kappa}<br> the TwirkEmote for Kappa will be:<ul>
* <li>EmoteID = 25
* <li>Pattern = Kappa
* <li>Indices = (0,5), (15,20)
*
* @author Gikkman
*
*/
public interface Emote {
/** Fetches the emotes ID as String. This became necessary after Twitch start
* including other characters than numbers in emote IDs
*
* @return The emotes ID
*/
String getEmoteIDString();
/** A list of pairs on indices. Each pair is a BEGIN-END pair of a emote occurrence in the message.<br><br>
*
* For example, if the message is: {@code Kappa PogChamp Kappa}<br> the list for emote 'Kappa' will include these pairs:<ul>
* <li> (0,5)
* <li> (15,20)
* </ul>
*
* @return The indices this emote takes up in the associated message
*/
LinkedList<EmoteIndices> getIndices();
/** The emote's pattern. For example: 'Kappa'
*
* @return The emote's pattern
*/
String getPattern();
/**Emote images can be downloaded from Twitch's server, and come in three
* sizes. Use this method to get the address for the emote.
*
* @param imageSize Emotes comes in three sizes. Specify which size you want
* @return The address for the emote's image
*/ | String getEmoteImageUrl(EMOTE_SIZE imageSize); |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/emote/EmoteParser.java | // Path: src/main/java/com/gikk/twirk/types/TagMap.java
// public interface TagMap extends Map<String, String>{
// //***********************************************************
// // PUBLIC
// //***********************************************************
// /**Fetches a certain field value that might have been present in the tag.
// * If the field was not present in the tag, or the field's value was empty,
// * this method returns <code>NULL</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if there was any. <code>NULL</code> otherwise
// */
// public String getAsString(String identifier);
//
// /**Fetches a certain field value that might have been present in the tag, and
// * tries to parse it into an <code>int</code>. If the field was not present in the tag,
// * or the field's value was empty, this method returns <code>-1</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if it was present and an int. <code>-1</code> otherwise
// */
// public int getAsInt(String identifier);
//
// /**Fetches a certain field value that might have been present in the tag, and
// * tries to parse it into a <code>long</code>. If the field was not present in the tag,
// * or the field's value was empty, this method returns <code>-1</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if it was present and a long. <code>-1</code> otherwise
// */
// long getAsLong(String identifier);
//
// /**Fetches a certain field value that might have been present in the tag, and
// * tries to parse it into a <code>boolean</code>. For parsing purpose, <code>1</code> is interpreted
// * as <code>true</code>, anything else as <code>false</code>.
// * If the field was not present in the tag, or the field's value was empty, this method returns <code>false</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if it was present and could be parsed to a boolean. <code>false</code> otherwise
// */
// public boolean getAsBoolean(String identifier);
//
// /**Creates a new TagMap using the default TagMap implementation.
// *
// * @param tag
// * @return the default tag map
// */
// static TagMap getDefault(String tag){
// return new TagMapImpl(tag);
// }
// }
| import com.gikk.twirk.types.TagMap;
import java.util.List; | package com.gikk.twirk.types.emote;
public interface EmoteParser {
/**
* @deprecated Use {{@link #parseEmotes(TagMap, String)} instead. This will be removed in a future release}
*/
@Deprecated
static List<Emote> parseEmotes(String content, String tag) { | // Path: src/main/java/com/gikk/twirk/types/TagMap.java
// public interface TagMap extends Map<String, String>{
// //***********************************************************
// // PUBLIC
// //***********************************************************
// /**Fetches a certain field value that might have been present in the tag.
// * If the field was not present in the tag, or the field's value was empty,
// * this method returns <code>NULL</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if there was any. <code>NULL</code> otherwise
// */
// public String getAsString(String identifier);
//
// /**Fetches a certain field value that might have been present in the tag, and
// * tries to parse it into an <code>int</code>. If the field was not present in the tag,
// * or the field's value was empty, this method returns <code>-1</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if it was present and an int. <code>-1</code> otherwise
// */
// public int getAsInt(String identifier);
//
// /**Fetches a certain field value that might have been present in the tag, and
// * tries to parse it into a <code>long</code>. If the field was not present in the tag,
// * or the field's value was empty, this method returns <code>-1</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if it was present and a long. <code>-1</code> otherwise
// */
// long getAsLong(String identifier);
//
// /**Fetches a certain field value that might have been present in the tag, and
// * tries to parse it into a <code>boolean</code>. For parsing purpose, <code>1</code> is interpreted
// * as <code>true</code>, anything else as <code>false</code>.
// * If the field was not present in the tag, or the field's value was empty, this method returns <code>false</code>
// *
// * @param identifier The fields identifier. See {@link TwitchTags}
// * @return The fields value, if it was present and could be parsed to a boolean. <code>false</code> otherwise
// */
// public boolean getAsBoolean(String identifier);
//
// /**Creates a new TagMap using the default TagMap implementation.
// *
// * @param tag
// * @return the default tag map
// */
// static TagMap getDefault(String tag){
// return new TagMapImpl(tag);
// }
// }
// Path: src/main/java/com/gikk/twirk/types/emote/EmoteParser.java
import com.gikk.twirk.types.TagMap;
import java.util.List;
package com.gikk.twirk.types.emote;
public interface EmoteParser {
/**
* @deprecated Use {{@link #parseEmotes(TagMap, String)} instead. This will be removed in a future release}
*/
@Deprecated
static List<Emote> parseEmotes(String content, String tag) { | TagMap tagMap = TagMap.getDefault(tag); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.