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
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) {
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) {
this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), STATE.parameter(state))));
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) {
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) {
this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), STATE.parameter(state))));
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state) {
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state) {
this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state))));
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) {
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client; /** * A basic {@link OAuth2AuthorizationRequest} implementation. * <p> * Note: Usually you don't need to instantiate this directly. * * @author Marten Gajda */ public final class BasicOAuth2AuthorizationRequest implements OAuth2AuthorizationRequest { private final FluentParameterList mParameters; public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) {
return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId)));
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) {
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state) { this(new Fluent(new BasicParameterList(RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) {
return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri)));
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
} public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri))); } @Override
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; } public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri))); } @Override
public OAuth2AuthorizationRequest withCodeChallenge(PkceCodeChallenge codeChallenge)
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri))); } @Override public OAuth2AuthorizationRequest withCodeChallenge(PkceCodeChallenge codeChallenge) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; public BasicOAuth2AuthorizationRequest(String responseType, OAuth2Scope scope, CharSequence state, ParameterList customParameters) { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri))); } @Override public OAuth2AuthorizationRequest withCodeChallenge(PkceCodeChallenge codeChallenge) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(
CODE_CHALLENGE_METHOD.parameter(codeChallenge.method()),
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE;
{ this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri))); } @Override public OAuth2AuthorizationRequest withCodeChallenge(PkceCodeChallenge codeChallenge) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith( CODE_CHALLENGE_METHOD.parameter(codeChallenge.method()),
// Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java // public interface PkceCodeChallenge // { // /** // * Returns a {@link Token} that identifies the method this code challenge uses. // * // * @return A {@link Token} containing the method name. // */ // Token method(); // // /** // * Returns the value of the code challenge. // * // * @return // */ // CharSequence challenge(); // } // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); // // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java // public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE); // Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequest.java import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE_METHOD; import static org.dmfs.oauth2.client.utils.Parameters.REDIRECT_URI; import static org.dmfs.oauth2.client.utils.Parameters.RESPONSE_TYPE; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import org.dmfs.oauth2.client.pkce.PkceCodeChallenge; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.encoding.XWwwFormUrlEncoded; import org.dmfs.rfc3986.parameters.FluentParameterList; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList; import org.dmfs.rfc3986.parameters.parametersets.Fluent; import org.dmfs.rfc3986.parameters.parametersets.Replacing; import java.net.URI; import java.net.URISyntaxException; import static org.dmfs.oauth2.client.utils.Parameters.CLIENT_ID; import static org.dmfs.oauth2.client.utils.Parameters.CODE_CHALLENGE; { this(new Fluent(new Replacing(customParameters, RESPONSE_TYPE.parameter(responseType), SCOPE.parameter(scope), STATE.parameter(state)))); } private BasicOAuth2AuthorizationRequest(FluentParameterList parameters) { mParameters = parameters; } @Override public OAuth2AuthorizationRequest withClientId(String clientId) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(CLIENT_ID.parameter(clientId))); } @Override public OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith(REDIRECT_URI.parameter(redirectUri))); } @Override public OAuth2AuthorizationRequest withCodeChallenge(PkceCodeChallenge codeChallenge) { return new BasicOAuth2AuthorizationRequest(mParameters.ratherWith( CODE_CHALLENGE_METHOD.parameter(codeChallenge.method()),
CODE_CHALLENGE.parameter(codeChallenge.challenge())));
dmfs/oauth2-essentials
src/test/java/org/dmfs/oauth2/client/http/responsehandlers/TokenResponseHandlerTest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java // public interface OAuth2AccessToken // { // /** // * Returns the actual access token String. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence accessToken() throws ProtocolException; // // /** // * Returns the access token type. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence tokenType() throws ProtocolException; // // /** // * Returns whether the response also contained a refresh token. // * // * @return // */ // public boolean hasRefreshToken(); // // /** // * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token. // * // * @return // * // * @throws NoSuchElementException // * If the token doesn't contain a refresh token. // * @throws ProtocolException // */ // public CharSequence refreshToken() throws ProtocolException; // // /** // * Returns the expected expiration date of the access token. // * // * @return // * // * @throws ProtocolException // */ // public DateTime expirationDate() throws ProtocolException; // // /** // * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known. // * // * @return An {@link OAuth2Scope}. // * // * @throws ProtocolException // */ // public OAuth2Scope scope() throws ProtocolException; // // /** // * Returns a value stored in the token response under the {@code parameterName}. // * // * @param parameterName // * the key under which the value is stored in the response // */ // public Optional<CharSequence> extraParameter(final String parameterName); // } // // Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java // public final class EmptyScope implements OAuth2Scope // { // public final static EmptyScope INSTANCE = new EmptyScope(); // // // @Override // public boolean isEmpty() // { // return true; // } // // // @Override // public boolean hasToken(String token) // { // // no tokens in here // return false; // } // // // @Override // public int tokenCount() // { // return 0; // } // // // @Override // public String toString() // { // return ""; // } // // // @Override // public boolean equals(Object obj) // { // if (!(obj instanceof OAuth2Scope)) // { // return false; // } // // return ((OAuth2Scope) obj).isEmpty(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.dmfs.httpessentials.HttpStatus; import org.dmfs.httpessentials.exceptions.ProtocolError; import org.dmfs.httpessentials.exceptions.ProtocolException; import org.dmfs.httpessentials.headers.EmptyHeaders; import org.dmfs.httpessentials.mockutils.entities.StaticMockResponseEntity; import org.dmfs.httpessentials.mockutils.responses.StaticMockResponse; import org.dmfs.httpessentials.types.StructuredMediaType; import org.dmfs.oauth2.client.OAuth2AccessToken; import org.dmfs.oauth2.client.scope.EmptyScope; import org.junit.Test; import java.io.IOException; import java.io.UnsupportedEncodingException;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.responsehandlers; /** * Test the {@link TokenResponseHandler}. * <p/> * TODO: also test some invalid responses. * * @author Marten Gajda <[email protected]> */ public class TokenResponseHandlerTest { @Test public void testHandleResponse() throws UnsupportedEncodingException, IOException, ProtocolError, ProtocolException { final String accessTokenResponse = "{" + "\"access_token\":\"2YotnFZFEjr1zCsicMWpAA\"," + "\"token_type\":\"example\"," + "\"expires_in\":3600," + "\"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\"," + "\"example_parameter\":\"example_value\"" + "}";
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java // public interface OAuth2AccessToken // { // /** // * Returns the actual access token String. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence accessToken() throws ProtocolException; // // /** // * Returns the access token type. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence tokenType() throws ProtocolException; // // /** // * Returns whether the response also contained a refresh token. // * // * @return // */ // public boolean hasRefreshToken(); // // /** // * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token. // * // * @return // * // * @throws NoSuchElementException // * If the token doesn't contain a refresh token. // * @throws ProtocolException // */ // public CharSequence refreshToken() throws ProtocolException; // // /** // * Returns the expected expiration date of the access token. // * // * @return // * // * @throws ProtocolException // */ // public DateTime expirationDate() throws ProtocolException; // // /** // * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known. // * // * @return An {@link OAuth2Scope}. // * // * @throws ProtocolException // */ // public OAuth2Scope scope() throws ProtocolException; // // /** // * Returns a value stored in the token response under the {@code parameterName}. // * // * @param parameterName // * the key under which the value is stored in the response // */ // public Optional<CharSequence> extraParameter(final String parameterName); // } // // Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java // public final class EmptyScope implements OAuth2Scope // { // public final static EmptyScope INSTANCE = new EmptyScope(); // // // @Override // public boolean isEmpty() // { // return true; // } // // // @Override // public boolean hasToken(String token) // { // // no tokens in here // return false; // } // // // @Override // public int tokenCount() // { // return 0; // } // // // @Override // public String toString() // { // return ""; // } // // // @Override // public boolean equals(Object obj) // { // if (!(obj instanceof OAuth2Scope)) // { // return false; // } // // return ((OAuth2Scope) obj).isEmpty(); // } // } // Path: src/test/java/org/dmfs/oauth2/client/http/responsehandlers/TokenResponseHandlerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.dmfs.httpessentials.HttpStatus; import org.dmfs.httpessentials.exceptions.ProtocolError; import org.dmfs.httpessentials.exceptions.ProtocolException; import org.dmfs.httpessentials.headers.EmptyHeaders; import org.dmfs.httpessentials.mockutils.entities.StaticMockResponseEntity; import org.dmfs.httpessentials.mockutils.responses.StaticMockResponse; import org.dmfs.httpessentials.types.StructuredMediaType; import org.dmfs.oauth2.client.OAuth2AccessToken; import org.dmfs.oauth2.client.scope.EmptyScope; import org.junit.Test; import java.io.IOException; import java.io.UnsupportedEncodingException; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.responsehandlers; /** * Test the {@link TokenResponseHandler}. * <p/> * TODO: also test some invalid responses. * * @author Marten Gajda <[email protected]> */ public class TokenResponseHandlerTest { @Test public void testHandleResponse() throws UnsupportedEncodingException, IOException, ProtocolError, ProtocolException { final String accessTokenResponse = "{" + "\"access_token\":\"2YotnFZFEjr1zCsicMWpAA\"," + "\"token_type\":\"example\"," + "\"expires_in\":3600," + "\"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\"," + "\"example_parameter\":\"example_value\"" + "}";
OAuth2AccessToken token = new TokenResponseHandler(EmptyScope.INSTANCE).handleResponse(
dmfs/oauth2-essentials
src/test/java/org/dmfs/oauth2/client/http/responsehandlers/TokenResponseHandlerTest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java // public interface OAuth2AccessToken // { // /** // * Returns the actual access token String. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence accessToken() throws ProtocolException; // // /** // * Returns the access token type. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence tokenType() throws ProtocolException; // // /** // * Returns whether the response also contained a refresh token. // * // * @return // */ // public boolean hasRefreshToken(); // // /** // * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token. // * // * @return // * // * @throws NoSuchElementException // * If the token doesn't contain a refresh token. // * @throws ProtocolException // */ // public CharSequence refreshToken() throws ProtocolException; // // /** // * Returns the expected expiration date of the access token. // * // * @return // * // * @throws ProtocolException // */ // public DateTime expirationDate() throws ProtocolException; // // /** // * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known. // * // * @return An {@link OAuth2Scope}. // * // * @throws ProtocolException // */ // public OAuth2Scope scope() throws ProtocolException; // // /** // * Returns a value stored in the token response under the {@code parameterName}. // * // * @param parameterName // * the key under which the value is stored in the response // */ // public Optional<CharSequence> extraParameter(final String parameterName); // } // // Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java // public final class EmptyScope implements OAuth2Scope // { // public final static EmptyScope INSTANCE = new EmptyScope(); // // // @Override // public boolean isEmpty() // { // return true; // } // // // @Override // public boolean hasToken(String token) // { // // no tokens in here // return false; // } // // // @Override // public int tokenCount() // { // return 0; // } // // // @Override // public String toString() // { // return ""; // } // // // @Override // public boolean equals(Object obj) // { // if (!(obj instanceof OAuth2Scope)) // { // return false; // } // // return ((OAuth2Scope) obj).isEmpty(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.dmfs.httpessentials.HttpStatus; import org.dmfs.httpessentials.exceptions.ProtocolError; import org.dmfs.httpessentials.exceptions.ProtocolException; import org.dmfs.httpessentials.headers.EmptyHeaders; import org.dmfs.httpessentials.mockutils.entities.StaticMockResponseEntity; import org.dmfs.httpessentials.mockutils.responses.StaticMockResponse; import org.dmfs.httpessentials.types.StructuredMediaType; import org.dmfs.oauth2.client.OAuth2AccessToken; import org.dmfs.oauth2.client.scope.EmptyScope; import org.junit.Test; import java.io.IOException; import java.io.UnsupportedEncodingException;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.responsehandlers; /** * Test the {@link TokenResponseHandler}. * <p/> * TODO: also test some invalid responses. * * @author Marten Gajda <[email protected]> */ public class TokenResponseHandlerTest { @Test public void testHandleResponse() throws UnsupportedEncodingException, IOException, ProtocolError, ProtocolException { final String accessTokenResponse = "{" + "\"access_token\":\"2YotnFZFEjr1zCsicMWpAA\"," + "\"token_type\":\"example\"," + "\"expires_in\":3600," + "\"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\"," + "\"example_parameter\":\"example_value\"" + "}";
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java // public interface OAuth2AccessToken // { // /** // * Returns the actual access token String. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence accessToken() throws ProtocolException; // // /** // * Returns the access token type. // * // * @return // * // * @throws ProtocolException // */ // public CharSequence tokenType() throws ProtocolException; // // /** // * Returns whether the response also contained a refresh token. // * // * @return // */ // public boolean hasRefreshToken(); // // /** // * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token. // * // * @return // * // * @throws NoSuchElementException // * If the token doesn't contain a refresh token. // * @throws ProtocolException // */ // public CharSequence refreshToken() throws ProtocolException; // // /** // * Returns the expected expiration date of the access token. // * // * @return // * // * @throws ProtocolException // */ // public DateTime expirationDate() throws ProtocolException; // // /** // * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known. // * // * @return An {@link OAuth2Scope}. // * // * @throws ProtocolException // */ // public OAuth2Scope scope() throws ProtocolException; // // /** // * Returns a value stored in the token response under the {@code parameterName}. // * // * @param parameterName // * the key under which the value is stored in the response // */ // public Optional<CharSequence> extraParameter(final String parameterName); // } // // Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java // public final class EmptyScope implements OAuth2Scope // { // public final static EmptyScope INSTANCE = new EmptyScope(); // // // @Override // public boolean isEmpty() // { // return true; // } // // // @Override // public boolean hasToken(String token) // { // // no tokens in here // return false; // } // // // @Override // public int tokenCount() // { // return 0; // } // // // @Override // public String toString() // { // return ""; // } // // // @Override // public boolean equals(Object obj) // { // if (!(obj instanceof OAuth2Scope)) // { // return false; // } // // return ((OAuth2Scope) obj).isEmpty(); // } // } // Path: src/test/java/org/dmfs/oauth2/client/http/responsehandlers/TokenResponseHandlerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.dmfs.httpessentials.HttpStatus; import org.dmfs.httpessentials.exceptions.ProtocolError; import org.dmfs.httpessentials.exceptions.ProtocolException; import org.dmfs.httpessentials.headers.EmptyHeaders; import org.dmfs.httpessentials.mockutils.entities.StaticMockResponseEntity; import org.dmfs.httpessentials.mockutils.responses.StaticMockResponse; import org.dmfs.httpessentials.types.StructuredMediaType; import org.dmfs.oauth2.client.OAuth2AccessToken; import org.dmfs.oauth2.client.scope.EmptyScope; import org.junit.Test; import java.io.IOException; import java.io.UnsupportedEncodingException; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.responsehandlers; /** * Test the {@link TokenResponseHandler}. * <p/> * TODO: also test some invalid responses. * * @author Marten Gajda <[email protected]> */ public class TokenResponseHandlerTest { @Test public void testHandleResponse() throws UnsupportedEncodingException, IOException, ProtocolError, ProtocolException { final String accessTokenResponse = "{" + "\"access_token\":\"2YotnFZFEjr1zCsicMWpAA\"," + "\"token_type\":\"example\"," + "\"expires_in\":3600," + "\"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\"," + "\"example_parameter\":\"example_value\"" + "}";
OAuth2AccessToken token = new TokenResponseHandler(EmptyScope.INSTANCE).handleResponse(
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // }
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // } // Path: src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */
public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier)
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // }
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>(
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // } // Path: src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>(
new GrantTypeParam("authorization_code"),
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // }
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>( new GrantTypeParam("authorization_code"),
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // } // Path: src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>( new GrantTypeParam("authorization_code"),
new AuthCodeParam(authorization),
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // }
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>( new GrantTypeParam("authorization_code"), new AuthCodeParam(authorization),
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // } // Path: src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>( new GrantTypeParam("authorization_code"), new AuthCodeParam(authorization),
new RedirectUriParam(redirectUri),
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // }
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>( new GrantTypeParam("authorization_code"), new AuthCodeParam(authorization), new RedirectUriParam(redirectUri),
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java // public interface OAuth2AuthCodeAuthorization // { // /** // * Returns the actual authorization code. // * // * @return // */ // public CharSequence code(); // // /** // * Returns the scope that this authorization has been granted for. // * // * @return // */ // public OAuth2Scope scope(); // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java // public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence> // { // // public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) // { // this(authorization.code()); // } // // // public AuthCodeParam(CharSequence authCode) // { // super("code", authCode); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/CodeVerifierParam.java // public final class CodeVerifierParam extends DelegatingPair<CharSequence, CharSequence> // { // public CodeVerifierParam(CharSequence codeVerifier) // { // super("code_verifier", codeVerifier); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java // public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence> // { // public GrantTypeParam(CharSequence grantType) // { // super("grant_type", grantType); // } // } // // Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RedirectUriParam.java // public final class RedirectUriParam extends DelegatingPair<CharSequence, CharSequence> // { // public RedirectUriParam(Uri redirectUri) // { // super("redirect_uri", new Text(redirectUri)); // } // } // Path: src/main/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequest.java import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity; import org.dmfs.jems.iterable.elementary.Seq; import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; import org.dmfs.oauth2.client.http.requests.parameters.AuthCodeParam; import org.dmfs.oauth2.client.http.requests.parameters.CodeVerifierParam; import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam; import org.dmfs.oauth2.client.http.requests.parameters.RedirectUriParam; import org.dmfs.rfc3986.Uri; /* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.http.requests; /** * Represents the requests to retrieve the token in an Authorization Code Grant. * * @author Marten Gajda */ public final class AuthorizationCodeTokenRequest extends AbstractAccessTokenRequest { /** * Creates a token request for an authorization code flow. * * @param authorization * The authorization code as returned by the authorization endpoint. * @param redirectUri * The client's redirect URI. * @param codeVerifier * The code verifier that was send with the authorization request. */ public AuthorizationCodeTokenRequest(OAuth2AuthCodeAuthorization authorization, Uri redirectUri, CharSequence codeVerifier) { super(authorization.scope(), new XWwwFormUrlEncodedEntity( new Seq<>( new GrantTypeParam("authorization_code"), new AuthCodeParam(authorization), new RedirectUriParam(redirectUri),
new CodeVerifierParam(codeVerifier))));
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/Version.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.io.Serializable; import java.util.Comparator; import java.util.List;
package io.arivera.oss.embedded.rabbitmq; /** * A class that provides information about a specific distribution artifact version of RabbitMQ. */ public interface Version { VersionComparator VERSION_COMPARATOR = new VersionComparator(); /** * @return a String formatted like {@code "3.6.5"} * * @see #getVersionAsString(CharSequence) */ String getVersionAsString(); /** * @return a String formatted like {@code "3_6_5"} if given {@code "_"} as separator. */ String getVersionAsString(CharSequence separator); /** * @return correct Archive Type for the given OS. */
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/Version.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.io.Serializable; import java.util.Comparator; import java.util.List; package io.arivera.oss.embedded.rabbitmq; /** * A class that provides information about a specific distribution artifact version of RabbitMQ. */ public interface Version { VersionComparator VERSION_COMPARATOR = new VersionComparator(); /** * @return a String formatted like {@code "3.6.5"} * * @see #getVersionAsString(CharSequence) */ String getVersionAsString(); /** * @return a String formatted like {@code "3_6_5"} if given {@code "_"} as separator. */ String getVersionAsString(CharSequence separator); /** * @return correct Archive Type for the given OS. */
ArchiveType getArchiveType(OperatingSystem operatingSystem);
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/Version.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.io.Serializable; import java.util.Comparator; import java.util.List;
package io.arivera.oss.embedded.rabbitmq; /** * A class that provides information about a specific distribution artifact version of RabbitMQ. */ public interface Version { VersionComparator VERSION_COMPARATOR = new VersionComparator(); /** * @return a String formatted like {@code "3.6.5"} * * @see #getVersionAsString(CharSequence) */ String getVersionAsString(); /** * @return a String formatted like {@code "3_6_5"} if given {@code "_"} as separator. */ String getVersionAsString(CharSequence separator); /** * @return correct Archive Type for the given OS. */
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/Version.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.io.Serializable; import java.util.Comparator; import java.util.List; package io.arivera.oss.embedded.rabbitmq; /** * A class that provides information about a specific distribution artifact version of RabbitMQ. */ public interface Version { VersionComparator VERSION_COMPARATOR = new VersionComparator(); /** * @return a String formatted like {@code "3.6.5"} * * @see #getVersionAsString(CharSequence) */ String getVersionAsString(); /** * @return a String formatted like {@code "3_6_5"} if given {@code "_"} as separator. */ String getVersionAsString(CharSequence separator); /** * @return correct Archive Type for the given OS. */
ArchiveType getArchiveType(OperatingSystem operatingSystem);
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/PredefinedVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List;
V3_8_0(new BaseVersion("3.8.0", ErlangVersion.V21_3)), V3_7_18(new BaseVersion("3.7.18", ErlangVersion.V20_3)), V3_7_7(new BaseVersion("3.7.7", ErlangVersion.V19_3_6_4)), V3_7_6(new BaseVersion("3.7.6", ErlangVersion.V19_3)), V3_7_5(new BaseVersion("3.7.5", ErlangVersion.V19_3)), V3_7_4(new BaseVersion("3.7.4", ErlangVersion.V19_3)), V3_7_3(new BaseVersion("3.7.3", ErlangVersion.V19_3)), V3_7_2(new BaseVersion("3.7.2", ErlangVersion.V19_3)), V3_7_1(new BaseVersion("3.7.1", ErlangVersion.V19_3)), V3_7_0(new BaseVersion("3.7.0", ErlangVersion.V19_3)), V3_6_16(new BaseVersion("3.6.16", ErlangVersion.V19_3)), V3_6_15(new BaseVersion("3.6.15", ErlangVersion.V19_3)), V3_6_14(new BaseVersion("3.6.14", ErlangVersion.R16B03)), V3_6_13(new BaseVersion("3.6.13", ErlangVersion.R16B03)), V3_6_12(new BaseVersion("3.6.12", ErlangVersion.R16B03)), V3_6_11(new BaseVersion("3.6.11", ErlangVersion.R16B03)), V3_6_10(new BaseVersion("3.6.10", ErlangVersion.R16B03)), V3_6_9(new BaseVersion("3.6.9", ErlangVersion.R16B03)), V3_6_8(new BaseVersion("3.6.8", ErlangVersion.R16B03)), V3_6_7(new BaseVersion("3.6.7", ErlangVersion.R16B03)), V3_6_6(new BaseVersion("3.6.6", ErlangVersion.R16B03)), V3_6_5(new BaseVersion("3.6.5", ErlangVersion.R16B03)), V3_6_4(new BaseVersion("3.6.4", ErlangVersion.R16B03)), V3_6_3(new BaseVersion("3.6.3", ErlangVersion.R16B03)), V3_6_2(new BaseVersion("3.6.2", ErlangVersion.R16B03)), V3_6_1(new BaseVersion("3.6.1", ErlangVersion.R16B03)), V3_6_0(new BaseVersion("3.6.0", ErlangVersion.R16B03)),
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/PredefinedVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List; V3_8_0(new BaseVersion("3.8.0", ErlangVersion.V21_3)), V3_7_18(new BaseVersion("3.7.18", ErlangVersion.V20_3)), V3_7_7(new BaseVersion("3.7.7", ErlangVersion.V19_3_6_4)), V3_7_6(new BaseVersion("3.7.6", ErlangVersion.V19_3)), V3_7_5(new BaseVersion("3.7.5", ErlangVersion.V19_3)), V3_7_4(new BaseVersion("3.7.4", ErlangVersion.V19_3)), V3_7_3(new BaseVersion("3.7.3", ErlangVersion.V19_3)), V3_7_2(new BaseVersion("3.7.2", ErlangVersion.V19_3)), V3_7_1(new BaseVersion("3.7.1", ErlangVersion.V19_3)), V3_7_0(new BaseVersion("3.7.0", ErlangVersion.V19_3)), V3_6_16(new BaseVersion("3.6.16", ErlangVersion.V19_3)), V3_6_15(new BaseVersion("3.6.15", ErlangVersion.V19_3)), V3_6_14(new BaseVersion("3.6.14", ErlangVersion.R16B03)), V3_6_13(new BaseVersion("3.6.13", ErlangVersion.R16B03)), V3_6_12(new BaseVersion("3.6.12", ErlangVersion.R16B03)), V3_6_11(new BaseVersion("3.6.11", ErlangVersion.R16B03)), V3_6_10(new BaseVersion("3.6.10", ErlangVersion.R16B03)), V3_6_9(new BaseVersion("3.6.9", ErlangVersion.R16B03)), V3_6_8(new BaseVersion("3.6.8", ErlangVersion.R16B03)), V3_6_7(new BaseVersion("3.6.7", ErlangVersion.R16B03)), V3_6_6(new BaseVersion("3.6.6", ErlangVersion.R16B03)), V3_6_5(new BaseVersion("3.6.5", ErlangVersion.R16B03)), V3_6_4(new BaseVersion("3.6.4", ErlangVersion.R16B03)), V3_6_3(new BaseVersion("3.6.3", ErlangVersion.R16B03)), V3_6_2(new BaseVersion("3.6.2", ErlangVersion.R16B03)), V3_6_1(new BaseVersion("3.6.1", ErlangVersion.R16B03)), V3_6_0(new BaseVersion("3.6.0", ErlangVersion.R16B03)),
V3_5_7(new BaseVersion("3.5.7", ErlangVersion.R13B03, ArchiveType.TAR_GZ)),
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/PredefinedVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List;
V3_4_4(new BaseVersion("3.4.4", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_3(new BaseVersion("3.4.3", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_2(new BaseVersion("3.4.2", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_1(new BaseVersion("3.4.1", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_0(new BaseVersion("3.4.0", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), LATEST(V3_8_14); final Version version; PredefinedVersion(Version version) { this.version = version; } @Override public List<Integer> getVersionComponents() { return version.getVersionComponents(); } @Override public String getVersionAsString() { return version.getVersionAsString(); } @Override public String getVersionAsString(CharSequence separator) { return version.getVersionAsString(separator); } @Override
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/PredefinedVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List; V3_4_4(new BaseVersion("3.4.4", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_3(new BaseVersion("3.4.3", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_2(new BaseVersion("3.4.2", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_1(new BaseVersion("3.4.1", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), V3_4_0(new BaseVersion("3.4.0", ErlangVersion.UNKNOWN, ArchiveType.TAR_GZ)), LATEST(V3_8_14); final Version version; PredefinedVersion(Version version) { this.version = version; } @Override public List<Integer> getVersionComponents() { return version.getVersionComponents(); } @Override public String getVersionAsString() { return version.getVersionAsString(); } @Override public String getVersionAsString(CharSequence separator) { return version.getVersionAsString(separator); } @Override
public ArchiveType getArchiveType(OperatingSystem operatingSystem) {
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/SingleArtifactRepository.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.net.URL;
package io.arivera.oss.embedded.rabbitmq; /** * Class used to allow for the user to specify a custom URL to download the RabbitMQ binary from. * <p> * Since this is basically a hardcoded URL, there's no ability to change the artifact to be downloaded based on * the OS the system is currently running. Use a {@link BaseVersion} if that capability is needed. * * @see EmbeddedRabbitMqConfig.Builder#downloadFrom(ArtifactRepository) * @see EmbeddedRabbitMqConfig.Builder#downloadFrom(URL, String) */ class SingleArtifactRepository implements ArtifactRepository { private final URL downloadSource; SingleArtifactRepository(URL downloadSource) { this.downloadSource = downloadSource; } @Override
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/SingleArtifactRepository.java import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.net.URL; package io.arivera.oss.embedded.rabbitmq; /** * Class used to allow for the user to specify a custom URL to download the RabbitMQ binary from. * <p> * Since this is basically a hardcoded URL, there's no ability to change the artifact to be downloaded based on * the OS the system is currently running. Use a {@link BaseVersion} if that capability is needed. * * @see EmbeddedRabbitMqConfig.Builder#downloadFrom(ArtifactRepository) * @see EmbeddedRabbitMqConfig.Builder#downloadFrom(URL, String) */ class SingleArtifactRepository implements ArtifactRepository { private final URL downloadSource; SingleArtifactRepository(URL downloadSource) { this.downloadSource = downloadSource; } @Override
public URL getUrl(Version version, OperatingSystem operatingSystem) {
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/bin/LoggingProcessListener.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // }
import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import org.slf4j.Logger; import org.zeroturnaround.exec.InvalidExitValueException; import org.zeroturnaround.exec.ProcessExecutor; import org.zeroturnaround.exec.ProcessResult; import org.zeroturnaround.exec.listener.ProcessListener;
package io.arivera.oss.embedded.rabbitmq.bin; class LoggingProcessListener extends ProcessListener { private final Logger logger; private ProcessExecutor executor; LoggingProcessListener(Logger logger) { this.logger = logger; } @Override public void beforeStart(ProcessExecutor executor) { this.executor = executor; logger.debug("Executing '{}' with environment vars: {}",
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/LoggingProcessListener.java import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import org.slf4j.Logger; import org.zeroturnaround.exec.InvalidExitValueException; import org.zeroturnaround.exec.ProcessExecutor; import org.zeroturnaround.exec.ProcessResult; import org.zeroturnaround.exec.listener.ProcessListener; package io.arivera.oss.embedded.rabbitmq.bin; class LoggingProcessListener extends ProcessListener { private final Logger logger; private ProcessExecutor executor; LoggingProcessListener(Logger logger) { this.logger = logger; } @Override public void beforeStart(ProcessExecutor executor) { this.executor = executor; logger.debug("Executing '{}' with environment vars: {}",
StringUtils.join(executor.getCommand(), " "), executor.getEnvironment());
AlejandroRivera/embedded-rabbitmq
src/test/java/io/arivera/oss/embedded/rabbitmq/helpers/ErlangVersionCheckerTest.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/ErlangVersion.java // public final class ErlangVersion { // public static final String V22_3 = "22.3"; // public static final String V21_3 = "21.3"; // public static final String V20_3 = "20.3"; // public static final String V19_3_6_4 = "19.3.6.4"; // public static final String V19_3 = "19.3"; // public static final String R16B03 = "r16b03"; // public static final String R13B03 = "r13b03"; // public static final String UNKNOWN = null; // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShell.java // public class ErlangShell { // private static final String LOGGER_TEMPLATE = "%s.Process.%s"; // // private static final String UNIX_ERL_COMMAND = "erl"; // // private final EmbeddedRabbitMqConfig config; // // /** // * Generic Constructor. // */ // public ErlangShell(final EmbeddedRabbitMqConfig config) { // this.config = config; // // } // // /** // * @return a String representing the Erlang version, such as {@code "18.2.1"} // * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. // */ // public String getErlangVersion() throws ErlangShellException { // String erlangShell = UNIX_ERL_COMMAND; // // Logger processOutputLogger = LoggerFactory.getLogger( // String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); // // Slf4jStream stream = Slf4jStream.of(processOutputLogger); // // final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() // .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") // .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) // .redirectError(stream.as(Level.WARN)) // .destroyOnExit() // .readOutput(true); // // try { // ProcessResult processResult = processExecutor.execute(); // int exitValue = processResult.getExitValue(); // if (exitValue == 0) { // return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" // } else { // throw new ErlangShellException("Erlang exited with status " + exitValue); // } // } catch (IOException | InterruptedException | TimeoutException e) { // throw new ErlangShellException("Exception executing Erlang shell command", e); // } // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShellException.java // public class ErlangShellException extends Exception { // public ErlangShellException(String message) { // super(message); // } // // public ErlangShellException(String message, Throwable cause) { // super(message, cause); // } // }
import io.arivera.oss.embedded.rabbitmq.ErlangVersion; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShell; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShellException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when;
package io.arivera.oss.embedded.rabbitmq.helpers; @RunWith(MockitoJUnitRunner.class) public class ErlangVersionCheckerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/ErlangVersion.java // public final class ErlangVersion { // public static final String V22_3 = "22.3"; // public static final String V21_3 = "21.3"; // public static final String V20_3 = "20.3"; // public static final String V19_3_6_4 = "19.3.6.4"; // public static final String V19_3 = "19.3"; // public static final String R16B03 = "r16b03"; // public static final String R13B03 = "r13b03"; // public static final String UNKNOWN = null; // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShell.java // public class ErlangShell { // private static final String LOGGER_TEMPLATE = "%s.Process.%s"; // // private static final String UNIX_ERL_COMMAND = "erl"; // // private final EmbeddedRabbitMqConfig config; // // /** // * Generic Constructor. // */ // public ErlangShell(final EmbeddedRabbitMqConfig config) { // this.config = config; // // } // // /** // * @return a String representing the Erlang version, such as {@code "18.2.1"} // * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. // */ // public String getErlangVersion() throws ErlangShellException { // String erlangShell = UNIX_ERL_COMMAND; // // Logger processOutputLogger = LoggerFactory.getLogger( // String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); // // Slf4jStream stream = Slf4jStream.of(processOutputLogger); // // final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() // .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") // .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) // .redirectError(stream.as(Level.WARN)) // .destroyOnExit() // .readOutput(true); // // try { // ProcessResult processResult = processExecutor.execute(); // int exitValue = processResult.getExitValue(); // if (exitValue == 0) { // return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" // } else { // throw new ErlangShellException("Erlang exited with status " + exitValue); // } // } catch (IOException | InterruptedException | TimeoutException e) { // throw new ErlangShellException("Exception executing Erlang shell command", e); // } // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShellException.java // public class ErlangShellException extends Exception { // public ErlangShellException(String message) { // super(message); // } // // public ErlangShellException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/test/java/io/arivera/oss/embedded/rabbitmq/helpers/ErlangVersionCheckerTest.java import io.arivera.oss.embedded.rabbitmq.ErlangVersion; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShell; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShellException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; package io.arivera.oss.embedded.rabbitmq.helpers; @RunWith(MockitoJUnitRunner.class) public class ErlangVersionCheckerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock
private ErlangShell shell;
AlejandroRivera/embedded-rabbitmq
src/test/java/io/arivera/oss/embedded/rabbitmq/helpers/ErlangVersionCheckerTest.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/ErlangVersion.java // public final class ErlangVersion { // public static final String V22_3 = "22.3"; // public static final String V21_3 = "21.3"; // public static final String V20_3 = "20.3"; // public static final String V19_3_6_4 = "19.3.6.4"; // public static final String V19_3 = "19.3"; // public static final String R16B03 = "r16b03"; // public static final String R13B03 = "r13b03"; // public static final String UNKNOWN = null; // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShell.java // public class ErlangShell { // private static final String LOGGER_TEMPLATE = "%s.Process.%s"; // // private static final String UNIX_ERL_COMMAND = "erl"; // // private final EmbeddedRabbitMqConfig config; // // /** // * Generic Constructor. // */ // public ErlangShell(final EmbeddedRabbitMqConfig config) { // this.config = config; // // } // // /** // * @return a String representing the Erlang version, such as {@code "18.2.1"} // * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. // */ // public String getErlangVersion() throws ErlangShellException { // String erlangShell = UNIX_ERL_COMMAND; // // Logger processOutputLogger = LoggerFactory.getLogger( // String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); // // Slf4jStream stream = Slf4jStream.of(processOutputLogger); // // final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() // .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") // .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) // .redirectError(stream.as(Level.WARN)) // .destroyOnExit() // .readOutput(true); // // try { // ProcessResult processResult = processExecutor.execute(); // int exitValue = processResult.getExitValue(); // if (exitValue == 0) { // return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" // } else { // throw new ErlangShellException("Erlang exited with status " + exitValue); // } // } catch (IOException | InterruptedException | TimeoutException e) { // throw new ErlangShellException("Exception executing Erlang shell command", e); // } // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShellException.java // public class ErlangShellException extends Exception { // public ErlangShellException(String message) { // super(message); // } // // public ErlangShellException(String message, Throwable cause) { // super(message, cause); // } // }
import io.arivera.oss.embedded.rabbitmq.ErlangVersion; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShell; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShellException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when;
package io.arivera.oss.embedded.rabbitmq.helpers; @RunWith(MockitoJUnitRunner.class) public class ErlangVersionCheckerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private ErlangShell shell; @Test public void parseR() { assertThat(ErlangVersionChecker.parse("R15B03-1"), equalTo(new int[] {15, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse("R15B"), equalTo(new int[] {15, 66, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("R11B-5"), equalTo(new int[] {11, 66, 0, 0, 0})); } @Test public void parseOtp() { assertThat(ErlangVersionChecker.parse("18.0"), equalTo(new int[] {18, 0, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("18.2.1"), equalTo(new int[] {18, 2, 1, 0, 0})); assertThat(ErlangVersionChecker.parse("18.3"), equalTo(new int[] {18, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("19.3.6.4"), equalTo(new int[] {19, 3, 6, 4, 0})); } @Test public void parseConstants() {
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/ErlangVersion.java // public final class ErlangVersion { // public static final String V22_3 = "22.3"; // public static final String V21_3 = "21.3"; // public static final String V20_3 = "20.3"; // public static final String V19_3_6_4 = "19.3.6.4"; // public static final String V19_3 = "19.3"; // public static final String R16B03 = "r16b03"; // public static final String R13B03 = "r13b03"; // public static final String UNKNOWN = null; // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShell.java // public class ErlangShell { // private static final String LOGGER_TEMPLATE = "%s.Process.%s"; // // private static final String UNIX_ERL_COMMAND = "erl"; // // private final EmbeddedRabbitMqConfig config; // // /** // * Generic Constructor. // */ // public ErlangShell(final EmbeddedRabbitMqConfig config) { // this.config = config; // // } // // /** // * @return a String representing the Erlang version, such as {@code "18.2.1"} // * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. // */ // public String getErlangVersion() throws ErlangShellException { // String erlangShell = UNIX_ERL_COMMAND; // // Logger processOutputLogger = LoggerFactory.getLogger( // String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); // // Slf4jStream stream = Slf4jStream.of(processOutputLogger); // // final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() // .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") // .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) // .redirectError(stream.as(Level.WARN)) // .destroyOnExit() // .readOutput(true); // // try { // ProcessResult processResult = processExecutor.execute(); // int exitValue = processResult.getExitValue(); // if (exitValue == 0) { // return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" // } else { // throw new ErlangShellException("Erlang exited with status " + exitValue); // } // } catch (IOException | InterruptedException | TimeoutException e) { // throw new ErlangShellException("Exception executing Erlang shell command", e); // } // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShellException.java // public class ErlangShellException extends Exception { // public ErlangShellException(String message) { // super(message); // } // // public ErlangShellException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/test/java/io/arivera/oss/embedded/rabbitmq/helpers/ErlangVersionCheckerTest.java import io.arivera.oss.embedded.rabbitmq.ErlangVersion; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShell; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShellException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; package io.arivera.oss.embedded.rabbitmq.helpers; @RunWith(MockitoJUnitRunner.class) public class ErlangVersionCheckerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private ErlangShell shell; @Test public void parseR() { assertThat(ErlangVersionChecker.parse("R15B03-1"), equalTo(new int[] {15, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse("R15B"), equalTo(new int[] {15, 66, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("R11B-5"), equalTo(new int[] {11, 66, 0, 0, 0})); } @Test public void parseOtp() { assertThat(ErlangVersionChecker.parse("18.0"), equalTo(new int[] {18, 0, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("18.2.1"), equalTo(new int[] {18, 2, 1, 0, 0})); assertThat(ErlangVersionChecker.parse("18.3"), equalTo(new int[] {18, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("19.3.6.4"), equalTo(new int[] {19, 3, 6, 4, 0})); } @Test public void parseConstants() {
assertThat(ErlangVersionChecker.parse(ErlangVersion.R16B03), equalTo(new int[] {16, 66, 3, 0, 0}));
AlejandroRivera/embedded-rabbitmq
src/test/java/io/arivera/oss/embedded/rabbitmq/helpers/ErlangVersionCheckerTest.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/ErlangVersion.java // public final class ErlangVersion { // public static final String V22_3 = "22.3"; // public static final String V21_3 = "21.3"; // public static final String V20_3 = "20.3"; // public static final String V19_3_6_4 = "19.3.6.4"; // public static final String V19_3 = "19.3"; // public static final String R16B03 = "r16b03"; // public static final String R13B03 = "r13b03"; // public static final String UNKNOWN = null; // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShell.java // public class ErlangShell { // private static final String LOGGER_TEMPLATE = "%s.Process.%s"; // // private static final String UNIX_ERL_COMMAND = "erl"; // // private final EmbeddedRabbitMqConfig config; // // /** // * Generic Constructor. // */ // public ErlangShell(final EmbeddedRabbitMqConfig config) { // this.config = config; // // } // // /** // * @return a String representing the Erlang version, such as {@code "18.2.1"} // * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. // */ // public String getErlangVersion() throws ErlangShellException { // String erlangShell = UNIX_ERL_COMMAND; // // Logger processOutputLogger = LoggerFactory.getLogger( // String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); // // Slf4jStream stream = Slf4jStream.of(processOutputLogger); // // final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() // .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") // .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) // .redirectError(stream.as(Level.WARN)) // .destroyOnExit() // .readOutput(true); // // try { // ProcessResult processResult = processExecutor.execute(); // int exitValue = processResult.getExitValue(); // if (exitValue == 0) { // return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" // } else { // throw new ErlangShellException("Erlang exited with status " + exitValue); // } // } catch (IOException | InterruptedException | TimeoutException e) { // throw new ErlangShellException("Exception executing Erlang shell command", e); // } // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShellException.java // public class ErlangShellException extends Exception { // public ErlangShellException(String message) { // super(message); // } // // public ErlangShellException(String message, Throwable cause) { // super(message, cause); // } // }
import io.arivera.oss.embedded.rabbitmq.ErlangVersion; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShell; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShellException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when;
package io.arivera.oss.embedded.rabbitmq.helpers; @RunWith(MockitoJUnitRunner.class) public class ErlangVersionCheckerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private ErlangShell shell; @Test public void parseR() { assertThat(ErlangVersionChecker.parse("R15B03-1"), equalTo(new int[] {15, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse("R15B"), equalTo(new int[] {15, 66, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("R11B-5"), equalTo(new int[] {11, 66, 0, 0, 0})); } @Test public void parseOtp() { assertThat(ErlangVersionChecker.parse("18.0"), equalTo(new int[] {18, 0, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("18.2.1"), equalTo(new int[] {18, 2, 1, 0, 0})); assertThat(ErlangVersionChecker.parse("18.3"), equalTo(new int[] {18, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("19.3.6.4"), equalTo(new int[] {19, 3, 6, 4, 0})); } @Test public void parseConstants() { assertThat(ErlangVersionChecker.parse(ErlangVersion.R16B03), equalTo(new int[] {16, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.R13B03), equalTo(new int[] {13, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V19_3), equalTo(new int[] {19, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V19_3_6_4), equalTo(new int[] {19, 3, 6, 4, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V20_3), equalTo(new int[] {20, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V21_3), equalTo(new int[] {21, 3, 0, 0, 0})); } @Test
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/ErlangVersion.java // public final class ErlangVersion { // public static final String V22_3 = "22.3"; // public static final String V21_3 = "21.3"; // public static final String V20_3 = "20.3"; // public static final String V19_3_6_4 = "19.3.6.4"; // public static final String V19_3 = "19.3"; // public static final String R16B03 = "r16b03"; // public static final String R13B03 = "r13b03"; // public static final String UNKNOWN = null; // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShell.java // public class ErlangShell { // private static final String LOGGER_TEMPLATE = "%s.Process.%s"; // // private static final String UNIX_ERL_COMMAND = "erl"; // // private final EmbeddedRabbitMqConfig config; // // /** // * Generic Constructor. // */ // public ErlangShell(final EmbeddedRabbitMqConfig config) { // this.config = config; // // } // // /** // * @return a String representing the Erlang version, such as {@code "18.2.1"} // * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. // */ // public String getErlangVersion() throws ErlangShellException { // String erlangShell = UNIX_ERL_COMMAND; // // Logger processOutputLogger = LoggerFactory.getLogger( // String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); // // Slf4jStream stream = Slf4jStream.of(processOutputLogger); // // final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() // .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") // .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) // .redirectError(stream.as(Level.WARN)) // .destroyOnExit() // .readOutput(true); // // try { // ProcessResult processResult = processExecutor.execute(); // int exitValue = processResult.getExitValue(); // if (exitValue == 0) { // return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" // } else { // throw new ErlangShellException("Erlang exited with status " + exitValue); // } // } catch (IOException | InterruptedException | TimeoutException e) { // throw new ErlangShellException("Exception executing Erlang shell command", e); // } // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/bin/ErlangShellException.java // public class ErlangShellException extends Exception { // public ErlangShellException(String message) { // super(message); // } // // public ErlangShellException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/test/java/io/arivera/oss/embedded/rabbitmq/helpers/ErlangVersionCheckerTest.java import io.arivera.oss.embedded.rabbitmq.ErlangVersion; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShell; import io.arivera.oss.embedded.rabbitmq.bin.ErlangShellException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; package io.arivera.oss.embedded.rabbitmq.helpers; @RunWith(MockitoJUnitRunner.class) public class ErlangVersionCheckerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private ErlangShell shell; @Test public void parseR() { assertThat(ErlangVersionChecker.parse("R15B03-1"), equalTo(new int[] {15, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse("R15B"), equalTo(new int[] {15, 66, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("R11B-5"), equalTo(new int[] {11, 66, 0, 0, 0})); } @Test public void parseOtp() { assertThat(ErlangVersionChecker.parse("18.0"), equalTo(new int[] {18, 0, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("18.2.1"), equalTo(new int[] {18, 2, 1, 0, 0})); assertThat(ErlangVersionChecker.parse("18.3"), equalTo(new int[] {18, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse("19.3.6.4"), equalTo(new int[] {19, 3, 6, 4, 0})); } @Test public void parseConstants() { assertThat(ErlangVersionChecker.parse(ErlangVersion.R16B03), equalTo(new int[] {16, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.R13B03), equalTo(new int[] {13, 66, 3, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V19_3), equalTo(new int[] {19, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V19_3_6_4), equalTo(new int[] {19, 3, 6, 4, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V20_3), equalTo(new int[] {20, 3, 0, 0, 0})); assertThat(ErlangVersionChecker.parse(ErlangVersion.V21_3), equalTo(new int[] {21, 3, 0, 0, 0})); } @Test
public void minVersionNotMet() throws ErlangShellException {
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/BaseVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import java.util.ArrayList; import java.util.List;
package io.arivera.oss.embedded.rabbitmq; /** * Class used when user wants to use a RabbitMQ version that's not defined in {@link PredefinedVersion} but that * still follows the binary artifact conventions. * * @see EmbeddedRabbitMqConfig.Builder#version(Version) */ public class BaseVersion implements Version { private static final String EXTRACTION_FOLDER = "rabbitmq_server-%s"; final List<Integer> versionComponents;
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/BaseVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import java.util.ArrayList; import java.util.List; package io.arivera.oss.embedded.rabbitmq; /** * Class used when user wants to use a RabbitMQ version that's not defined in {@link PredefinedVersion} but that * still follows the binary artifact conventions. * * @see EmbeddedRabbitMqConfig.Builder#version(Version) */ public class BaseVersion implements Version { private static final String EXTRACTION_FOLDER = "rabbitmq_server-%s"; final List<Integer> versionComponents;
final ArchiveType unixArchiveType;
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/BaseVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import java.util.ArrayList; import java.util.List;
* or @{code null} if no version check should be performed. * @param unixArchiveType The type of packaging used for the Unix/Mac binaries, typically {@link ArchiveType#TAR_XZ} * @param windowsArchiveType The type of packaging used for Windows binaries, typically {@link ArchiveType#ZIP} * * @see <a href="https://www.rabbitmq.com/which-erlang.html">RabbitMQ Erlang Version Requirements</a> */ public BaseVersion(String semanticVersion, String minErlangVersion, ArchiveType unixArchiveType, ArchiveType windowsArchiveType) { String[] versionComponents = semanticVersion.split("\\."); this.versionComponents = new ArrayList<>(versionComponents.length); for (String versionComponent : versionComponents) { this.versionComponents.add(Integer.parseInt(versionComponent)); } this.unixArchiveType = unixArchiveType; this.windowsArchiveType = windowsArchiveType; this.minErlangVersion = minErlangVersion; } @Override public List<Integer> getVersionComponents() { return versionComponents; } @Override public String getVersionAsString() { return getVersionAsString("."); } @Override public String getVersionAsString(CharSequence separator) {
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/BaseVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import java.util.ArrayList; import java.util.List; * or @{code null} if no version check should be performed. * @param unixArchiveType The type of packaging used for the Unix/Mac binaries, typically {@link ArchiveType#TAR_XZ} * @param windowsArchiveType The type of packaging used for Windows binaries, typically {@link ArchiveType#ZIP} * * @see <a href="https://www.rabbitmq.com/which-erlang.html">RabbitMQ Erlang Version Requirements</a> */ public BaseVersion(String semanticVersion, String minErlangVersion, ArchiveType unixArchiveType, ArchiveType windowsArchiveType) { String[] versionComponents = semanticVersion.split("\\."); this.versionComponents = new ArrayList<>(versionComponents.length); for (String versionComponent : versionComponents) { this.versionComponents.add(Integer.parseInt(versionComponent)); } this.unixArchiveType = unixArchiveType; this.windowsArchiveType = windowsArchiveType; this.minErlangVersion = minErlangVersion; } @Override public List<Integer> getVersionComponents() { return versionComponents; } @Override public String getVersionAsString() { return getVersionAsString("."); } @Override public String getVersionAsString(CharSequence separator) {
return StringUtils.join(versionComponents, separator);
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/BaseVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import java.util.ArrayList; import java.util.List;
* @see <a href="https://www.rabbitmq.com/which-erlang.html">RabbitMQ Erlang Version Requirements</a> */ public BaseVersion(String semanticVersion, String minErlangVersion, ArchiveType unixArchiveType, ArchiveType windowsArchiveType) { String[] versionComponents = semanticVersion.split("\\."); this.versionComponents = new ArrayList<>(versionComponents.length); for (String versionComponent : versionComponents) { this.versionComponents.add(Integer.parseInt(versionComponent)); } this.unixArchiveType = unixArchiveType; this.windowsArchiveType = windowsArchiveType; this.minErlangVersion = minErlangVersion; } @Override public List<Integer> getVersionComponents() { return versionComponents; } @Override public String getVersionAsString() { return getVersionAsString("."); } @Override public String getVersionAsString(CharSequence separator) { return StringUtils.join(versionComponents, separator); } @Override
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/StringUtils.java // public class StringUtils { // // /** // * Joins the elements of the provided collection into a single String containing the provided list of elements. // * <p> // * No delimiter is added before or after the list. // * <p> // * Empty collections return an empty String. // */ // public static <T> String join(Collection<T> collection, CharSequence joinedBy) { // if (collection.isEmpty()) { // return ""; // } // StringBuilder stringBuilder = new StringBuilder(256); // for (T t : collection) { // stringBuilder.append(t.toString()).append(joinedBy); // } // return stringBuilder.substring(0, stringBuilder.length() - joinedBy.length()); // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/BaseVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import io.arivera.oss.embedded.rabbitmq.util.StringUtils; import java.util.ArrayList; import java.util.List; * @see <a href="https://www.rabbitmq.com/which-erlang.html">RabbitMQ Erlang Version Requirements</a> */ public BaseVersion(String semanticVersion, String minErlangVersion, ArchiveType unixArchiveType, ArchiveType windowsArchiveType) { String[] versionComponents = semanticVersion.split("\\."); this.versionComponents = new ArrayList<>(versionComponents.length); for (String versionComponent : versionComponents) { this.versionComponents.add(Integer.parseInt(versionComponent)); } this.unixArchiveType = unixArchiveType; this.windowsArchiveType = windowsArchiveType; this.minErlangVersion = minErlangVersion; } @Override public List<Integer> getVersionComponents() { return versionComponents; } @Override public String getVersionAsString() { return getVersionAsString("."); } @Override public String getVersionAsString(CharSequence separator) { return StringUtils.join(versionComponents, separator); } @Override
public ArchiveType getArchiveType(OperatingSystem operatingSystem) {
AlejandroRivera/embedded-rabbitmq
src/test/java/io/arivera/oss/embedded/rabbitmq/OfficialArtifactRepositoryTest.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import org.junit.Test; import java.net.URL; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat;
package io.arivera.oss.embedded.rabbitmq; public class OfficialArtifactRepositoryTest { @Test public void downloadForWindows() throws Exception { URL url = OfficialArtifactRepository.RABBITMQ
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/test/java/io/arivera/oss/embedded/rabbitmq/OfficialArtifactRepositoryTest.java import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import org.junit.Test; import java.net.URL; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; package io.arivera.oss.embedded.rabbitmq; public class OfficialArtifactRepositoryTest { @Test public void downloadForWindows() throws Exception { URL url = OfficialArtifactRepository.RABBITMQ
.getUrl(PredefinedVersion.V3_6_5, OperatingSystem.WINDOWS);
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/OfficialArtifactRepository.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map;
package io.arivera.oss.embedded.rabbitmq; /** * A list of the official repositories where RabbitMQ publishes their artifacts. * * @see EmbeddedRabbitMqConfig.Builder#downloadFrom(ArtifactRepository) */ public enum OfficialArtifactRepository implements ArtifactRepository { /** * @deprecated in favor of {@link #GITHUB} since starting with v3.7.0, this repository is no longer updated. * More info: <a href="http://www.rabbitmq.com/blog/2018/02/05/whats-new-in-rabbitmq-3-7/">Package Distribution Changes</a>. */ @Deprecated RABBITMQ("http://www.rabbitmq.com/releases/rabbitmq-server/%sv%s/rabbitmq-server-%s-%s.%s") { @Override
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/OfficialArtifactRepository.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; package io.arivera.oss.embedded.rabbitmq; /** * A list of the official repositories where RabbitMQ publishes their artifacts. * * @see EmbeddedRabbitMqConfig.Builder#downloadFrom(ArtifactRepository) */ public enum OfficialArtifactRepository implements ArtifactRepository { /** * @deprecated in favor of {@link #GITHUB} since starting with v3.7.0, this repository is no longer updated. * More info: <a href="http://www.rabbitmq.com/blog/2018/02/05/whats-new-in-rabbitmq-3-7/">Package Distribution Changes</a>. */ @Deprecated RABBITMQ("http://www.rabbitmq.com/releases/rabbitmq-server/%sv%s/rabbitmq-server-%s-%s.%s") { @Override
public URL getUrl(Version version, OperatingSystem operatingSystem) {
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/OfficialArtifactRepository.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map;
} @Override protected String getFolderVersion(Version version) { if (Version.VERSION_COMPARATOR.compare(version, PredefinedVersion.V3_7_0) < 0) { return version.getVersionAsString("_"); } return super.getFolderVersion(version); } }, BINTRAY("https://dl.bintray.com/rabbitmq/all/rabbitmq-server/%s%s/rabbitmq-server-%s-%s.%s"), ; private static Map<OperatingSystem, String> downloadPlatformName = new HashMap<>(3); static { downloadPlatformName.put(OperatingSystem.MAC_OS, "mac-standalone"); downloadPlatformName.put(OperatingSystem.UNIX, "generic-unix"); downloadPlatformName.put(OperatingSystem.WINDOWS, "windows"); } private final String urlPattern; OfficialArtifactRepository(String urlPattern) { this.urlPattern = urlPattern; } @Override public URL getUrl(Version version, OperatingSystem operatingSystem) { String artifactPlatform = getArtifactPlatform(version, operatingSystem);
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/OfficialArtifactRepository.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; } @Override protected String getFolderVersion(Version version) { if (Version.VERSION_COMPARATOR.compare(version, PredefinedVersion.V3_7_0) < 0) { return version.getVersionAsString("_"); } return super.getFolderVersion(version); } }, BINTRAY("https://dl.bintray.com/rabbitmq/all/rabbitmq-server/%s%s/rabbitmq-server-%s-%s.%s"), ; private static Map<OperatingSystem, String> downloadPlatformName = new HashMap<>(3); static { downloadPlatformName.put(OperatingSystem.MAC_OS, "mac-standalone"); downloadPlatformName.put(OperatingSystem.UNIX, "generic-unix"); downloadPlatformName.put(OperatingSystem.WINDOWS, "windows"); } private final String urlPattern; OfficialArtifactRepository(String urlPattern) { this.urlPattern = urlPattern; } @Override public URL getUrl(Version version, OperatingSystem operatingSystem) { String artifactPlatform = getArtifactPlatform(version, operatingSystem);
ArchiveType archiveType = version.getArchiveType(operatingSystem);
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/UnknownVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List;
package io.arivera.oss.embedded.rabbitmq; /** * A class that represents the RabbitMQ Version that is downloaded from the {@link SingleArtifactRepository}. * <p> * The only thing we care about from the custom download artifact is the folder name where the RabbitMQ installation * can be found. We don't care about the version number, the Erlang version required, etc. */ class UnknownVersion implements Version { private final String appFolderName; public UnknownVersion(String appFolderName) { this.appFolderName = appFolderName; } @Override public String getExtractionFolder() { return appFolderName; } @Override public String getMinimumErlangVersion() { return ErlangVersion.UNKNOWN; } @Override public String getVersionAsString() { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override public String getVersionAsString(CharSequence separator) { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/UnknownVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List; package io.arivera.oss.embedded.rabbitmq; /** * A class that represents the RabbitMQ Version that is downloaded from the {@link SingleArtifactRepository}. * <p> * The only thing we care about from the custom download artifact is the folder name where the RabbitMQ installation * can be found. We don't care about the version number, the Erlang version required, etc. */ class UnknownVersion implements Version { private final String appFolderName; public UnknownVersion(String appFolderName) { this.appFolderName = appFolderName; } @Override public String getExtractionFolder() { return appFolderName; } @Override public String getMinimumErlangVersion() { return ErlangVersion.UNKNOWN; } @Override public String getVersionAsString() { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override public String getVersionAsString(CharSequence separator) { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override
public ArchiveType getArchiveType(OperatingSystem operatingSystem) {
AlejandroRivera/embedded-rabbitmq
src/main/java/io/arivera/oss/embedded/rabbitmq/UnknownVersion.java
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // }
import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List;
package io.arivera.oss.embedded.rabbitmq; /** * A class that represents the RabbitMQ Version that is downloaded from the {@link SingleArtifactRepository}. * <p> * The only thing we care about from the custom download artifact is the folder name where the RabbitMQ installation * can be found. We don't care about the version number, the Erlang version required, etc. */ class UnknownVersion implements Version { private final String appFolderName; public UnknownVersion(String appFolderName) { this.appFolderName = appFolderName; } @Override public String getExtractionFolder() { return appFolderName; } @Override public String getMinimumErlangVersion() { return ErlangVersion.UNKNOWN; } @Override public String getVersionAsString() { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override public String getVersionAsString(CharSequence separator) { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override
// Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/ArchiveType.java // public enum ArchiveType { // // TAR_GZ, TAR_XZ, ZIP; // // public String getExtension() { // return name().toLowerCase(Locale.US).replace("_", "."); // } // // public boolean matches(String filesname) { // return filesname.endsWith(getExtension()); // } // } // // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/util/OperatingSystem.java // public enum OperatingSystem { // // WINDOWS, MAC_OS, UNIX; // // /** // * Returns the right instance of the Operation System. // * // * @see SystemUtils#IS_OS_MAC // * @see SystemUtils#IS_OS_WINDOWS // */ // public static OperatingSystem detect() { // if (SystemUtils.IS_OS_MAC) { // return MAC_OS; // } else if (SystemUtils.IS_OS_WINDOWS) { // return WINDOWS; // } else { // return UNIX; // } // } // // } // Path: src/main/java/io/arivera/oss/embedded/rabbitmq/UnknownVersion.java import io.arivera.oss.embedded.rabbitmq.util.ArchiveType; import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem; import java.util.List; package io.arivera.oss.embedded.rabbitmq; /** * A class that represents the RabbitMQ Version that is downloaded from the {@link SingleArtifactRepository}. * <p> * The only thing we care about from the custom download artifact is the folder name where the RabbitMQ installation * can be found. We don't care about the version number, the Erlang version required, etc. */ class UnknownVersion implements Version { private final String appFolderName; public UnknownVersion(String appFolderName) { this.appFolderName = appFolderName; } @Override public String getExtractionFolder() { return appFolderName; } @Override public String getMinimumErlangVersion() { return ErlangVersion.UNKNOWN; } @Override public String getVersionAsString() { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override public String getVersionAsString(CharSequence separator) { throw new RuntimeException("This value isn't needed for custom downloads."); } @Override
public ArchiveType getArchiveType(OperatingSystem operatingSystem) {
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutResponse.java
// Path: src/main/java/com/twocheckout/model/Authorization.java // public class Authorization { // private String type; // private String responseCode; // private String currencyCode; // private String orderNumber; // private String transactionId; // private String recurrentInstallmentId; // private String responseMsg; // private String merchantOrderId; // private BigDecimal total; // private Lineitems[] lineItems; // // public String getType() { return type; } // public String getResponseCode() { return responseCode; } // public String getCurrencyCode() { return currencyCode; } // public String getOrderNumber() { return orderNumber; } // public String getTransactionId() { return transactionId; } // public String getRecurrentInstallmentId() { return recurrentInstallmentId; } // public String getResponseMsg() { return responseMsg; } // public String getMerchantOrderId() { return merchantOrderId; } // public BigDecimal getTotal() { return total; } // public Lineitems[] getLineitems() { return lineItems; } // }
import com.twocheckout.model.Authorization;
package com.twocheckout; public class TwocheckoutResponse { private String response_code; private String response_message; private String product_id; private String assigned_product_id; private String option_id;
// Path: src/main/java/com/twocheckout/model/Authorization.java // public class Authorization { // private String type; // private String responseCode; // private String currencyCode; // private String orderNumber; // private String transactionId; // private String recurrentInstallmentId; // private String responseMsg; // private String merchantOrderId; // private BigDecimal total; // private Lineitems[] lineItems; // // public String getType() { return type; } // public String getResponseCode() { return responseCode; } // public String getCurrencyCode() { return currencyCode; } // public String getOrderNumber() { return orderNumber; } // public String getTransactionId() { return transactionId; } // public String getRecurrentInstallmentId() { return recurrentInstallmentId; } // public String getResponseMsg() { return responseMsg; } // public String getMerchantOrderId() { return merchantOrderId; } // public BigDecimal getTotal() { return total; } // public Lineitems[] getLineitems() { return lineItems; } // } // Path: src/main/java/com/twocheckout/TwocheckoutResponse.java import com.twocheckout.model.Authorization; package com.twocheckout; public class TwocheckoutResponse { private String response_code; private String response_message; private String product_id; private String assigned_product_id; private String option_id;
private Authorization response;
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutSale.java
// Path: src/main/java/com/twocheckout/model/Sale.java // public class Sale { // private long sale_id; // private String ip_address; // private String ip_country; // private RecurringDecline recurring_decline; // private Invoice[] invoices; // private Comments[] comments; // // public long getSaleId() { // return sale_id; // } // // public String getIpAddress() { // return ip_address; // } // // public String getIpCountry() { // return ip_country; // } // // public RecurringDecline getRecurringDecline() { // return recurring_decline; // } // // public Invoice[] getInvoices() { // return invoices; // } // // public Comments[] getComments() { // return comments; // } // // public TwocheckoutResponse refund(HashMap<String, String> args) throws TwocheckoutException { // args.put("sale_id", String.valueOf(sale_id)); // String urlSuffix = "/api/sales/refund_invoice"; // String response = TwocheckoutApi.post(urlSuffix, args); // TwocheckoutResponse responseObj = new Gson().fromJson(response, TwocheckoutResponse.class); // return responseObj; // } // // public TwocheckoutResponse comment(HashMap<String, String> args) throws TwocheckoutException { // args.put("sale_id", String.valueOf(sale_id));; // String urlSuffix = "/api/sales/create_comment"; // String response = TwocheckoutApi.post(urlSuffix, args); // TwocheckoutResponse responseObj = new Gson().fromJson(response, TwocheckoutResponse.class); // return responseObj; // } // // public TwocheckoutResponse ship(HashMap<String, String> args) throws TwocheckoutException { // args.put("sale_id", String.valueOf(sale_id)); // String urlSuffix = "/api/sales/mark_shipped"; // String response = TwocheckoutApi.post(urlSuffix, args); // TwocheckoutResponse responseObj = new Gson().fromJson(response, TwocheckoutResponse.class); // return responseObj; // } // // public TwocheckoutResponse stop() throws TwocheckoutException { // String urlSuffix = "/api/sales/stop_lineitem_recurring"; // Invoice invoice = invoices[invoices.length-1]; // Lineitem[] lineitems = invoice.getLineitems(); // String stopped_lineitems = null; // StringBuffer stopped_lineitems_buffer = new StringBuffer(); // HashMap<String, String> params = new HashMap<String, String>(); // for(int i = 0;i< lineitems.length; i++){ // if (lineitems[i].getBilling().getRecurringStatus() != null) { // if (lineitems[i].getBilling().getRecurringStatus().equals("active")) { // params.put("lineitem_id", String.valueOf(lineitems[i].getBilling().getLineitemId())); // String response = TwocheckoutApi.post(urlSuffix, params); // TwocheckoutResponse resultObj = new Gson().fromJson(response, TwocheckoutResponse.class); // if(resultObj.getResponseCode().equals("OK")) { // stopped_lineitems_buffer.append(",").append(String.valueOf(lineitems[i].getLineitemID())); // } // } // } // } // stopped_lineitems = stopped_lineitems_buffer.toString(); // TwocheckoutResponse responseObj = new TwocheckoutResponse(); // if (stopped_lineitems.length() == 0) { // responseObj.setResponseCode("OK"); // responseObj.setResponseMessage("No active recurring lineitems."); // } else { // stopped_lineitems = stopped_lineitems.substring(1); // responseObj.setResponseCode("OK"); // responseObj.setResponseMessage(stopped_lineitems); // } // return responseObj; // } // // public Sale refresh() throws TwocheckoutException { // HashMap<String, String> args = new HashMap<String, String>(); // args.put("sale_id", String.valueOf(sale_id)); // String urlSuffix = "/api/sales/detail_sale"; // String response = TwocheckoutApi.get(urlSuffix, args); // TwocheckoutSale responseObj = new Gson().fromJson(response, TwocheckoutSale.class); // response = new Gson().toJson(responseObj.sale); // Sale resultObj = new Gson().fromJson(response, Sale.class); // return resultObj; // } // // } // // Path: src/main/java/com/twocheckout/model/SaleList.java // public class SaleList { // private PageInfo page_info; // private Sales[] sale_summary; // // public PageInfo getPageInfo() { // return page_info; // } // // public Sales[] getSales() { // return sale_summary; // } // }
import com.google.gson.Gson; import com.twocheckout.model.Sale; import com.twocheckout.model.SaleList; import java.util.HashMap;
package com.twocheckout; public class TwocheckoutSale extends TwocheckoutApi { public Sale sale; public static Sale retrieve(String sale_id) throws TwocheckoutException { String urlSuffix = "/api/sales/detail_sale"; HashMap<String, String> args = new HashMap<String, String>(); args.put("sale_id", sale_id); String response = TwocheckoutApi.get(urlSuffix, args); TwocheckoutSale resultObj = new Gson().fromJson(response, TwocheckoutSale.class); response = new Gson().toJson(resultObj.sale); Sale responseObj = new Gson().fromJson(response, Sale.class); return responseObj; }
// Path: src/main/java/com/twocheckout/model/Sale.java // public class Sale { // private long sale_id; // private String ip_address; // private String ip_country; // private RecurringDecline recurring_decline; // private Invoice[] invoices; // private Comments[] comments; // // public long getSaleId() { // return sale_id; // } // // public String getIpAddress() { // return ip_address; // } // // public String getIpCountry() { // return ip_country; // } // // public RecurringDecline getRecurringDecline() { // return recurring_decline; // } // // public Invoice[] getInvoices() { // return invoices; // } // // public Comments[] getComments() { // return comments; // } // // public TwocheckoutResponse refund(HashMap<String, String> args) throws TwocheckoutException { // args.put("sale_id", String.valueOf(sale_id)); // String urlSuffix = "/api/sales/refund_invoice"; // String response = TwocheckoutApi.post(urlSuffix, args); // TwocheckoutResponse responseObj = new Gson().fromJson(response, TwocheckoutResponse.class); // return responseObj; // } // // public TwocheckoutResponse comment(HashMap<String, String> args) throws TwocheckoutException { // args.put("sale_id", String.valueOf(sale_id));; // String urlSuffix = "/api/sales/create_comment"; // String response = TwocheckoutApi.post(urlSuffix, args); // TwocheckoutResponse responseObj = new Gson().fromJson(response, TwocheckoutResponse.class); // return responseObj; // } // // public TwocheckoutResponse ship(HashMap<String, String> args) throws TwocheckoutException { // args.put("sale_id", String.valueOf(sale_id)); // String urlSuffix = "/api/sales/mark_shipped"; // String response = TwocheckoutApi.post(urlSuffix, args); // TwocheckoutResponse responseObj = new Gson().fromJson(response, TwocheckoutResponse.class); // return responseObj; // } // // public TwocheckoutResponse stop() throws TwocheckoutException { // String urlSuffix = "/api/sales/stop_lineitem_recurring"; // Invoice invoice = invoices[invoices.length-1]; // Lineitem[] lineitems = invoice.getLineitems(); // String stopped_lineitems = null; // StringBuffer stopped_lineitems_buffer = new StringBuffer(); // HashMap<String, String> params = new HashMap<String, String>(); // for(int i = 0;i< lineitems.length; i++){ // if (lineitems[i].getBilling().getRecurringStatus() != null) { // if (lineitems[i].getBilling().getRecurringStatus().equals("active")) { // params.put("lineitem_id", String.valueOf(lineitems[i].getBilling().getLineitemId())); // String response = TwocheckoutApi.post(urlSuffix, params); // TwocheckoutResponse resultObj = new Gson().fromJson(response, TwocheckoutResponse.class); // if(resultObj.getResponseCode().equals("OK")) { // stopped_lineitems_buffer.append(",").append(String.valueOf(lineitems[i].getLineitemID())); // } // } // } // } // stopped_lineitems = stopped_lineitems_buffer.toString(); // TwocheckoutResponse responseObj = new TwocheckoutResponse(); // if (stopped_lineitems.length() == 0) { // responseObj.setResponseCode("OK"); // responseObj.setResponseMessage("No active recurring lineitems."); // } else { // stopped_lineitems = stopped_lineitems.substring(1); // responseObj.setResponseCode("OK"); // responseObj.setResponseMessage(stopped_lineitems); // } // return responseObj; // } // // public Sale refresh() throws TwocheckoutException { // HashMap<String, String> args = new HashMap<String, String>(); // args.put("sale_id", String.valueOf(sale_id)); // String urlSuffix = "/api/sales/detail_sale"; // String response = TwocheckoutApi.get(urlSuffix, args); // TwocheckoutSale responseObj = new Gson().fromJson(response, TwocheckoutSale.class); // response = new Gson().toJson(responseObj.sale); // Sale resultObj = new Gson().fromJson(response, Sale.class); // return resultObj; // } // // } // // Path: src/main/java/com/twocheckout/model/SaleList.java // public class SaleList { // private PageInfo page_info; // private Sales[] sale_summary; // // public PageInfo getPageInfo() { // return page_info; // } // // public Sales[] getSales() { // return sale_summary; // } // } // Path: src/main/java/com/twocheckout/TwocheckoutSale.java import com.google.gson.Gson; import com.twocheckout.model.Sale; import com.twocheckout.model.SaleList; import java.util.HashMap; package com.twocheckout; public class TwocheckoutSale extends TwocheckoutApi { public Sale sale; public static Sale retrieve(String sale_id) throws TwocheckoutException { String urlSuffix = "/api/sales/detail_sale"; HashMap<String, String> args = new HashMap<String, String>(); args.put("sale_id", sale_id); String response = TwocheckoutApi.get(urlSuffix, args); TwocheckoutSale resultObj = new Gson().fromJson(response, TwocheckoutSale.class); response = new Gson().toJson(resultObj.sale); Sale responseObj = new Gson().fromJson(response, Sale.class); return responseObj; }
public static SaleList list(HashMap<String, String> args) throws TwocheckoutException {
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutCharge.java
// Path: src/main/java/com/twocheckout/model/Authorization.java // public class Authorization { // private String type; // private String responseCode; // private String currencyCode; // private String orderNumber; // private String transactionId; // private String recurrentInstallmentId; // private String responseMsg; // private String merchantOrderId; // private BigDecimal total; // private Lineitems[] lineItems; // // public String getType() { return type; } // public String getResponseCode() { return responseCode; } // public String getCurrencyCode() { return currencyCode; } // public String getOrderNumber() { return orderNumber; } // public String getTransactionId() { return transactionId; } // public String getRecurrentInstallmentId() { return recurrentInstallmentId; } // public String getResponseMsg() { return responseMsg; } // public String getMerchantOrderId() { return merchantOrderId; } // public BigDecimal getTotal() { return total; } // public Lineitems[] getLineitems() { return lineItems; } // }
import com.google.gson.Gson; import com.twocheckout.model.Authorization; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair;
for (Map.Entry<String, String> entry : args.entrySet()) { html.append( "<input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\"" + entry.getValue() + "\"/>\n" ); } html.append( "<input type=\"submit\" value=\"Checkout\" />\n</form>\n" ); return html.toString(); } public static String submit(HashMap<String, String> args) { StringBuilder html = new StringBuilder(); html.append( "<form id=\"2checkout\" action=\"" + checkout_url() + "/checkout/purchase\" method=\"post\">\n" ); for (Map.Entry<String, String> entry : args.entrySet()) { html.append( "<input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\"" + entry.getValue() + "\"/>\n" ); } html.append( "</form>\n" ); html.append( "<script type=\"text/javascript\">document.getElementById('2checkout').submit();</script>" ); return html.toString(); } public static String url(HashMap<String, String> args) { String url = checkout_url() + "/checkout/purchase?"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : args.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String paramString = URLEncodedUtils.format(params, "utf-8"); return url += paramString; }
// Path: src/main/java/com/twocheckout/model/Authorization.java // public class Authorization { // private String type; // private String responseCode; // private String currencyCode; // private String orderNumber; // private String transactionId; // private String recurrentInstallmentId; // private String responseMsg; // private String merchantOrderId; // private BigDecimal total; // private Lineitems[] lineItems; // // public String getType() { return type; } // public String getResponseCode() { return responseCode; } // public String getCurrencyCode() { return currencyCode; } // public String getOrderNumber() { return orderNumber; } // public String getTransactionId() { return transactionId; } // public String getRecurrentInstallmentId() { return recurrentInstallmentId; } // public String getResponseMsg() { return responseMsg; } // public String getMerchantOrderId() { return merchantOrderId; } // public BigDecimal getTotal() { return total; } // public Lineitems[] getLineitems() { return lineItems; } // } // Path: src/main/java/com/twocheckout/TwocheckoutCharge.java import com.google.gson.Gson; import com.twocheckout.model.Authorization; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; for (Map.Entry<String, String> entry : args.entrySet()) { html.append( "<input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\"" + entry.getValue() + "\"/>\n" ); } html.append( "<input type=\"submit\" value=\"Checkout\" />\n</form>\n" ); return html.toString(); } public static String submit(HashMap<String, String> args) { StringBuilder html = new StringBuilder(); html.append( "<form id=\"2checkout\" action=\"" + checkout_url() + "/checkout/purchase\" method=\"post\">\n" ); for (Map.Entry<String, String> entry : args.entrySet()) { html.append( "<input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\"" + entry.getValue() + "\"/>\n" ); } html.append( "</form>\n" ); html.append( "<script type=\"text/javascript\">document.getElementById('2checkout').submit();</script>" ); return html.toString(); } public static String url(HashMap<String, String> args) { String url = checkout_url() + "/checkout/purchase?"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : args.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String paramString = URLEncodedUtils.format(params, "utf-8"); return url += paramString; }
public static Authorization authorize(HashMap<String, Object> args) throws TwocheckoutException {
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutApi.java
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // }
import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); httpclient.getConnectionManager().shutdown(); checkStatusCodeAuth(response, responseBody); if (responseBody != null) { return responseBody; } } catch (TwocheckoutException e) { throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) {
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // } // Path: src/main/java/com/twocheckout/TwocheckoutApi.java import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); httpclient.getConnectionManager().shutdown(); checkStatusCodeAuth(response, responseBody); if (responseBody != null) { return responseBody; } } catch (TwocheckoutException e) { throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) {
Errors errors = new Gson().fromJson(responseBody, Errors.class);
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutApi.java
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // }
import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); httpclient.getConnectionManager().shutdown(); checkStatusCodeAuth(response, responseBody); if (responseBody != null) { return responseBody; } } catch (TwocheckoutException e) { throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Errors errors = new Gson().fromJson(responseBody, Errors.class);
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // } // Path: src/main/java/com/twocheckout/TwocheckoutApi.java import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); httpclient.getConnectionManager().shutdown(); checkStatusCodeAuth(response, responseBody); if (responseBody != null) { return responseBody; } } catch (TwocheckoutException e) { throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Errors errors = new Gson().fromJson(responseBody, Errors.class);
Error[] error = errors.getErrors();
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutApi.java
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // }
import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
} catch (TwocheckoutException e) { throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Errors errors = new Gson().fromJson(responseBody, Errors.class); Error[] error = errors.getErrors(); throw new TwocheckoutException(error[0].getMessage(), error[0].getCode()); } } private static void checkStatusCodeAuth(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK && status.getStatusCode() != HttpStatus.SC_ACCEPTED ) {
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // } // Path: src/main/java/com/twocheckout/TwocheckoutApi.java import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; } catch (TwocheckoutException e) { throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Errors errors = new Gson().fromJson(responseBody, Errors.class); Error[] error = errors.getErrors(); throw new TwocheckoutException(error[0].getMessage(), error[0].getCode()); } } private static void checkStatusCodeAuth(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK && status.getStatusCode() != HttpStatus.SC_ACCEPTED ) {
AuthExceptions exceptions = new Gson().fromJson(responseBody, AuthExceptions.class);
2Checkout/2checkout-java
src/main/java/com/twocheckout/TwocheckoutApi.java
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // }
import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Errors errors = new Gson().fromJson(responseBody, Errors.class); Error[] error = errors.getErrors(); throw new TwocheckoutException(error[0].getMessage(), error[0].getCode()); } } private static void checkStatusCodeAuth(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK && status.getStatusCode() != HttpStatus.SC_ACCEPTED ) { AuthExceptions exceptions = new Gson().fromJson(responseBody, AuthExceptions.class);
// Path: src/main/java/com/twocheckout/model/AuthException.java // public class AuthException { // private String errorMsg; // private String errorCode; // private String httpStatus; // // public String getMessage() { // return errorMsg; // } // public String getCode() { // return errorCode; // } // public String getStatus() { return httpStatus; } // } // // Path: src/main/java/com/twocheckout/model/AuthExceptions.java // public class AuthExceptions { // private AuthException exception; // // public AuthException getAuthExceptions() { // return exception; // } // } // // Path: src/main/java/com/twocheckout/model/Error.java // public class Error { // private String message; // private String code; // // public String getMessage() { // return message; // } // public void setMessage(String message) { // this.message = message; // } // public String getCode() { // return code; // } // public void setCode(String code) { // this.code = code; // } // } // // Path: src/main/java/com/twocheckout/model/Errors.java // public class Errors { // private Error[] errors; // // public Error[] getErrors() { // return errors; // } // // public void setErrors(Error[] errors) { // this.errors = errors; // } // } // Path: src/main/java/com/twocheckout/TwocheckoutApi.java import com.google.gson.Gson; import com.twocheckout.model.AuthException; import com.twocheckout.model.AuthExceptions; import com.twocheckout.model.Error; import com.twocheckout.model.Errors; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.StringEntity; import org.apache.http.entity.ContentType; import javax.net.ssl.SSLContext; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; throw new TwocheckoutException(e.getMessage(), e.getCode()); } catch (Exception e) { throw new TwocheckoutException(e.getMessage()); } return mainObject; } public static String addLocationToUrl(String url, List<NameValuePair> params){ if(!url.endsWith("?")) url += "?"; String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; } private static void checkStatusCodeAdmin(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Errors errors = new Gson().fromJson(responseBody, Errors.class); Error[] error = errors.getErrors(); throw new TwocheckoutException(error[0].getMessage(), error[0].getCode()); } } private static void checkStatusCodeAuth(HttpResponse response, String responseBody) throws TwocheckoutException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK && status.getStatusCode() != HttpStatus.SC_ACCEPTED ) { AuthExceptions exceptions = new Gson().fromJson(responseBody, AuthExceptions.class);
AuthException exception = exceptions.getAuthExceptions();
hdweiss/codemap
src/com/hdweiss/codemap/view/workspace/FindDeclarationTask.java
// Path: src/com/hdweiss/codemap/data/CscopeEntry.java // public class CscopeEntry { // private static int CSCOPE_FILE = 1; // private static int CSCOPE_ACTUALNAME = 2; // private static int CSCOPE_NAME = 4; // private static int CSCOPE_LINENUMBER = 3; // // public String actualName = ""; // public String name = ""; // public String file = ""; // public int lineNumber = -1; // private int endLine = -2; // // private static Pattern CscopeEntryPattern = Pattern.compile("(\\S*)\\s(\\S*)\\s(\\d*)\\s(.*)"); // public CscopeEntry(String line) { // Matcher matcher = CscopeEntryPattern.matcher(line); // // if(matcher.find()) { // this.file = matcher.group(CSCOPE_FILE); // this.name = matcher.group(CSCOPE_NAME); // this.actualName = matcher.group(CSCOPE_ACTUALNAME); // this.lineNumber = Integer.parseInt(matcher.group(CSCOPE_LINENUMBER)); // } else // throw new IllegalArgumentException("Couldn't parse " + line); // } // // public int getEndLine(CscopeWrapper cscopeWrapper) { // if (endLine == -2) // endLine = cscopeWrapper.getFunctionEndLine(this); // return endLine; // } // // public String getUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + name; // } else // return file + ":" + name; // } // // public String getActualUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + actualName; // } else // return file + ":" + actualName; // } // // public String toString() { // return file + ":" + name + "@" + lineNumber; // } // }
import java.util.ArrayList; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.hdweiss.codemap.data.CscopeEntry;
package com.hdweiss.codemap.view.workspace; public class FindDeclarationTask extends AsyncTask<Object, Object, Object> { private ProgressDialog dialog; private Context context; private FindDeclarationCallback callback; private String url; private WorkspaceController controller;
// Path: src/com/hdweiss/codemap/data/CscopeEntry.java // public class CscopeEntry { // private static int CSCOPE_FILE = 1; // private static int CSCOPE_ACTUALNAME = 2; // private static int CSCOPE_NAME = 4; // private static int CSCOPE_LINENUMBER = 3; // // public String actualName = ""; // public String name = ""; // public String file = ""; // public int lineNumber = -1; // private int endLine = -2; // // private static Pattern CscopeEntryPattern = Pattern.compile("(\\S*)\\s(\\S*)\\s(\\d*)\\s(.*)"); // public CscopeEntry(String line) { // Matcher matcher = CscopeEntryPattern.matcher(line); // // if(matcher.find()) { // this.file = matcher.group(CSCOPE_FILE); // this.name = matcher.group(CSCOPE_NAME); // this.actualName = matcher.group(CSCOPE_ACTUALNAME); // this.lineNumber = Integer.parseInt(matcher.group(CSCOPE_LINENUMBER)); // } else // throw new IllegalArgumentException("Couldn't parse " + line); // } // // public int getEndLine(CscopeWrapper cscopeWrapper) { // if (endLine == -2) // endLine = cscopeWrapper.getFunctionEndLine(this); // return endLine; // } // // public String getUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + name; // } else // return file + ":" + name; // } // // public String getActualUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + actualName; // } else // return file + ":" + actualName; // } // // public String toString() { // return file + ":" + name + "@" + lineNumber; // } // } // Path: src/com/hdweiss/codemap/view/workspace/FindDeclarationTask.java import java.util.ArrayList; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.hdweiss.codemap.data.CscopeEntry; package com.hdweiss.codemap.view.workspace; public class FindDeclarationTask extends AsyncTask<Object, Object, Object> { private ProgressDialog dialog; private Context context; private FindDeclarationCallback callback; private String url; private WorkspaceController controller;
private ArrayList<CscopeEntry> entries;
hdweiss/codemap
src/com/hdweiss/codemap/view/workspace/fragments/CodeMapAnnotation.java
// Path: src/com/hdweiss/codemap/util/CodeMapPoint.java // public class CodeMapPoint extends PointF implements Serializable { // private static final long serialVersionUID = 1L; // // public CodeMapPoint() { // super(); // } // // public CodeMapPoint(float x, float y) { // super(x, y); // } // // public CodeMapPoint(PointF point) { // super(point.x, point.y); // } // // private void writeObject(final java.io.ObjectOutputStream out) // throws IOException { // out.writeFloat(x); // out.writeFloat(y); // } // // private void readObject(final java.io.ObjectInputStream in) // throws IOException { // x = in.readFloat(); // y = in.readFloat(); // } // }
import android.content.Context; import android.util.AttributeSet; import android.widget.EditText; import com.hdweiss.codemap.util.CodeMapPoint;
package com.hdweiss.codemap.view.workspace.fragments; public class CodeMapAnnotation extends CodeMapItem { private EditText editText; public CodeMapAnnotation(Context context, AttributeSet attrs) { this(context, null, ""); }
// Path: src/com/hdweiss/codemap/util/CodeMapPoint.java // public class CodeMapPoint extends PointF implements Serializable { // private static final long serialVersionUID = 1L; // // public CodeMapPoint() { // super(); // } // // public CodeMapPoint(float x, float y) { // super(x, y); // } // // public CodeMapPoint(PointF point) { // super(point.x, point.y); // } // // private void writeObject(final java.io.ObjectOutputStream out) // throws IOException { // out.writeFloat(x); // out.writeFloat(y); // } // // private void readObject(final java.io.ObjectInputStream in) // throws IOException { // x = in.readFloat(); // y = in.readFloat(); // } // } // Path: src/com/hdweiss/codemap/view/workspace/fragments/CodeMapAnnotation.java import android.content.Context; import android.util.AttributeSet; import android.widget.EditText; import com.hdweiss.codemap.util.CodeMapPoint; package com.hdweiss.codemap.view.workspace.fragments; public class CodeMapAnnotation extends CodeMapItem { private EditText editText; public CodeMapAnnotation(Context context, AttributeSet attrs) { this(context, null, ""); }
public CodeMapAnnotation(Context context, CodeMapPoint point, String contents) {
hdweiss/codemap
src/com/hdweiss/codemap/data/ProjectController.java
// Path: src/com/hdweiss/codemap/util/SyntaxHighlighter.java // public class SyntaxHighlighter { // // private final String[] C_KEYWORDS = { // "auto", // "break", // "case", // "char", // "const", // "continue", // "default", // "do", // "double", // "else", // "enum", // "extern", // "float", // "for", // "goto", // "if", // "int", // "long", // "register", // "return", // "short", // "unsigned", // "signed", // "sizeof", // "static", // "struct", // "switch", // "typedef", // "union", // "void", // "volatile", // "while" }; // // private String content; // // public SyntaxHighlighter(String contents) { // this.content = contents; // } // // public SpannableString formatToHtml() { // formatNewline(); // highlightKeywords(); // highlightComments(); // // SpannableString spannableString = new SpannableString( // Html.fromHtml(content)); // return spannableString; // } // // private void formatNewline() { // content = content.replaceAll("\n\r", "<br />"); // content = content.replaceAll("\n", "<br />"); // content = content.replaceAll("\r", "<br />"); // } // // private void highlightKeywords() { // for(String keyword: C_KEYWORDS) { // content = content.replaceAll(keyword, "<font color=\"purple\">" + keyword + "</font>"); // } // } // // private void highlightComments() { // content = content.replaceAll("/\\*.*?\\*/", "<font color=\"green\">$0</font>"); // content = content.replaceAll("//[^\n]*?\n", "<font color=\"green\">$0</font>"); // } // // public void markupReferences(ArrayList<CscopeEntry> references) { // StringBuilder result = new StringBuilder(content); // for(CscopeEntry entry: references) { // Matcher matcher = Pattern.compile("(" + Pattern.quote(entry.actualName) + ")(?:\\s?\\()").matcher(result); // // if(matcher.find()) { // result.insert(matcher.end(1), "</a>"); // result.insert(matcher.start(1), "<a href=\"" + entry.actualName + "\">"); // } // } // content = result.toString(); // } // }
import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import android.content.Context; import android.text.SpannableString; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.hdweiss.codemap.util.SyntaxHighlighter;
final String fileName = getFileFromUrl(url); final String functionName = getFunctionFromUrl(url); ArrayList<CscopeEntry> allEntries = cscopeWrapper.getAllEntries( functionName, fileName); return allEntries; } /** * Call in case of full url. */ // TODO Refactor, only createCodeMapItem() calls this public SpannableString getFunctionSource(String url) { final String fileName = getFileFromUrl(url); final String functionName = getFunctionFromUrl(url); try { ArrayList<CscopeEntry> allEntries = cscopeWrapper.getAllEntries( functionName, fileName); return getFunctionSource(allEntries.get(0)); } catch (IllegalArgumentException e) { Log.e("CodeMap", e.getLocalizedMessage()); return new SpannableString(""); } } public SpannableString getFunctionSource(CscopeEntry entry) { String content = cscopeWrapper.getFunction(entry).trim();
// Path: src/com/hdweiss/codemap/util/SyntaxHighlighter.java // public class SyntaxHighlighter { // // private final String[] C_KEYWORDS = { // "auto", // "break", // "case", // "char", // "const", // "continue", // "default", // "do", // "double", // "else", // "enum", // "extern", // "float", // "for", // "goto", // "if", // "int", // "long", // "register", // "return", // "short", // "unsigned", // "signed", // "sizeof", // "static", // "struct", // "switch", // "typedef", // "union", // "void", // "volatile", // "while" }; // // private String content; // // public SyntaxHighlighter(String contents) { // this.content = contents; // } // // public SpannableString formatToHtml() { // formatNewline(); // highlightKeywords(); // highlightComments(); // // SpannableString spannableString = new SpannableString( // Html.fromHtml(content)); // return spannableString; // } // // private void formatNewline() { // content = content.replaceAll("\n\r", "<br />"); // content = content.replaceAll("\n", "<br />"); // content = content.replaceAll("\r", "<br />"); // } // // private void highlightKeywords() { // for(String keyword: C_KEYWORDS) { // content = content.replaceAll(keyword, "<font color=\"purple\">" + keyword + "</font>"); // } // } // // private void highlightComments() { // content = content.replaceAll("/\\*.*?\\*/", "<font color=\"green\">$0</font>"); // content = content.replaceAll("//[^\n]*?\n", "<font color=\"green\">$0</font>"); // } // // public void markupReferences(ArrayList<CscopeEntry> references) { // StringBuilder result = new StringBuilder(content); // for(CscopeEntry entry: references) { // Matcher matcher = Pattern.compile("(" + Pattern.quote(entry.actualName) + ")(?:\\s?\\()").matcher(result); // // if(matcher.find()) { // result.insert(matcher.end(1), "</a>"); // result.insert(matcher.start(1), "<a href=\"" + entry.actualName + "\">"); // } // } // content = result.toString(); // } // } // Path: src/com/hdweiss/codemap/data/ProjectController.java import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import android.content.Context; import android.text.SpannableString; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.hdweiss.codemap.util.SyntaxHighlighter; final String fileName = getFileFromUrl(url); final String functionName = getFunctionFromUrl(url); ArrayList<CscopeEntry> allEntries = cscopeWrapper.getAllEntries( functionName, fileName); return allEntries; } /** * Call in case of full url. */ // TODO Refactor, only createCodeMapItem() calls this public SpannableString getFunctionSource(String url) { final String fileName = getFileFromUrl(url); final String functionName = getFunctionFromUrl(url); try { ArrayList<CscopeEntry> allEntries = cscopeWrapper.getAllEntries( functionName, fileName); return getFunctionSource(allEntries.get(0)); } catch (IllegalArgumentException e) { Log.e("CodeMap", e.getLocalizedMessage()); return new SpannableString(""); } } public SpannableString getFunctionSource(CscopeEntry entry) { String content = cscopeWrapper.getFunction(entry).trim();
SyntaxHighlighter highlighter = new SyntaxHighlighter(content);
hdweiss/codemap
src/com/hdweiss/codemap/data/SerializableLink.java
// Path: src/com/hdweiss/codemap/view/workspace/fragments/CodeMapLink.java // public class CodeMapLink { // // public CodeMapItem parent; // public CodeMapItem child; // // public float yOffset = 0; // // public CodeMapLink(CodeMapItem parent, CodeMapItem child, float yOffset) { // this.parent = parent; // this.child = child; // this.yOffset = yOffset; // } // // public boolean hasItem(CodeMapItem item) { // return parent == item || child == item; // } // // public void doDraw(Canvas canvas) { // Paint paint = new Paint(); // // float startX = parent.getX() + parent.getWidth(); // float startY = parent.getY() + yOffset; // // float endX = child.getX(); // float endY = child.getTitleViewYMid(); // // float midX = (startX + endX) / 2; // // canvas.drawLine(startX, startY, midX, startY, paint); // canvas.drawLine(midX, startY, midX, endY, paint); // canvas.drawLine(midX, endY, endX, endY, paint); // } // // public String toString() { // return parent.getUrl() + "->" + child.getUrl(); // } // }
import java.io.Serializable; import java.util.UUID; import com.hdweiss.codemap.view.workspace.fragments.CodeMapLink;
package com.hdweiss.codemap.data; public class SerializableLink implements Serializable { private static final long serialVersionUID = 1L; public UUID parent; public UUID child; public float offset; public SerializableLink(UUID parent, UUID child, float offset) { this.parent = parent; this.child = child; this.offset = offset; }
// Path: src/com/hdweiss/codemap/view/workspace/fragments/CodeMapLink.java // public class CodeMapLink { // // public CodeMapItem parent; // public CodeMapItem child; // // public float yOffset = 0; // // public CodeMapLink(CodeMapItem parent, CodeMapItem child, float yOffset) { // this.parent = parent; // this.child = child; // this.yOffset = yOffset; // } // // public boolean hasItem(CodeMapItem item) { // return parent == item || child == item; // } // // public void doDraw(Canvas canvas) { // Paint paint = new Paint(); // // float startX = parent.getX() + parent.getWidth(); // float startY = parent.getY() + yOffset; // // float endX = child.getX(); // float endY = child.getTitleViewYMid(); // // float midX = (startX + endX) / 2; // // canvas.drawLine(startX, startY, midX, startY, paint); // canvas.drawLine(midX, startY, midX, endY, paint); // canvas.drawLine(midX, endY, endX, endY, paint); // } // // public String toString() { // return parent.getUrl() + "->" + child.getUrl(); // } // } // Path: src/com/hdweiss/codemap/data/SerializableLink.java import java.io.Serializable; import java.util.UUID; import com.hdweiss.codemap.view.workspace.fragments.CodeMapLink; package com.hdweiss.codemap.data; public class SerializableLink implements Serializable { private static final long serialVersionUID = 1L; public UUID parent; public UUID child; public float offset; public SerializableLink(UUID parent, UUID child, float offset) { this.parent = parent; this.child = child; this.offset = offset; }
public SerializableLink(CodeMapLink link) {
hdweiss/codemap
src/com/hdweiss/codemap/util/ZoomableLinearLayout.java
// Path: src/com/hdweiss/codemap/view/workspace/WorkspaceView.java // public class WorkspaceView extends ZoomableAbsoluteLayout { // // private GestureDetector gestureDetector; // private ScaleGestureDetector scaleDetector; // private Scroller scroller; // // public ArrayList<CodeMapItem> items = new ArrayList<CodeMapItem>(); // private ArrayList<CodeMapLink> links = new ArrayList<CodeMapLink>(); // private WorkspaceController controller; // // public WorkspaceView(Context context, AttributeSet attrs) { // super(context, attrs); // // this.scroller = new Scroller(getContext()); // this.gestureDetector = new GestureDetector(getContext(), new CodeMapGestureListener(this, scroller)); // this.scaleDetector = new ScaleGestureDetector(getContext(), new CodeMapScaleListener(this)); // // setWillNotDraw(false); // setFocusable(false); // } // // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // // canvas.save(); // canvas.scale(getScaleFactor(), getScaleFactor()); // // for(CodeMapLink link: links) // link.doDraw(canvas); // // canvas.restore(); // } // // public void refresh() { // invalidate(); // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // super.onTouchEvent(event); // // scaleDetector.onTouchEvent(event); // gestureDetector.onTouchEvent(event); // // updateScroll(); // return true; // } // // private void updateScroll() { // if(scroller.computeScrollOffset()) { // float dx = (scroller.getStartX() - scroller.getFinalX()); // float dy = (scroller.getStartY() - scroller.getFinalY()); // scrollBy(-(int)dx, -(int)dy); // } // } // // // public void addMapItem(CodeMapItem item) { // if (items.contains(item)) // return; // // addView(item); // items.add(item); // item.setCodeMapView(this); // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void addMapLink(CodeMapLink link) { // if(link.parent != null && link.child != null) { // links.add(link); // refresh(); // } // } // // public void remove(CodeMapItem item) { // removeView(item); // items.remove(item); // item.setCodeMapView(null); // // Iterator<CodeMapLink> linksIt = links.iterator(); // while(linksIt.hasNext()) { // CodeMapLink link = linksIt.next(); // if(link.hasItem(item)) // linksIt.remove(); // } // // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void clear() { // removeAllViews(); // items.clear(); // links.clear(); // } // // // public void moveFragment(CodeMapItem item, CodeMapPoint position) { // item.setPosition(position); // moveFragment(item); // } // // public void moveFragment(CodeMapItem item) { // CollisionManager.pushItems(item, this.items); // } // // public CodeMapItem getMapFragmentAtPoint(CodeMapCursorPoint cursorPoint) { // CodeMapPoint point = cursorPoint.getCodeMapPoint(this); // for (CodeMapItem view : items) { // if (view.contains(point)) // return view; // } // return null; // } // // // public void setController(WorkspaceController controller) { // this.controller = controller; // } // // public WorkspaceController getController() { // return this.controller; // } // // public WorkspaceState getState() { // WorkspaceState state = new WorkspaceState(controller.getWorkspaceName()); // // for(CodeMapItem item: items) // state.items.add(new SerializableItem(item)); // // for(CodeMapLink link: links) // state.links.add(new SerializableLink(link)); // // state.zoom = getScaleFactor(); // state.scrollX = getScrollX(); // state.scrollY = getScrollY(); // return state; // } // // // TODO Make more efficient // public ArrayList<CodeMapItem> getDeclarations(String url) { // ArrayList<CodeMapItem> result = new ArrayList<CodeMapItem>(); // Iterator<CodeMapItem> i = this.items.iterator(); // while (i.hasNext()) { // CodeMapItem item = i.next(); // // if (item.getUrl().equals(url)) // result.add(item); // } // // return result; // } // // public void setScroll(float x, float y) { // setScrollX((int) x); // setScrollY((int) y); // } // // public void setFontSize(int fontSize) { // for (CodeMapItem item: this.items) { // item.setFontSize(fontSize); // } // } // }
import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.view.ViewParent; import android.widget.LinearLayout; import com.hdweiss.codemap.view.workspace.WorkspaceView;
package com.hdweiss.codemap.util; public class ZoomableLinearLayout extends LinearLayout { public ZoomableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public float getScaleFactor() {
// Path: src/com/hdweiss/codemap/view/workspace/WorkspaceView.java // public class WorkspaceView extends ZoomableAbsoluteLayout { // // private GestureDetector gestureDetector; // private ScaleGestureDetector scaleDetector; // private Scroller scroller; // // public ArrayList<CodeMapItem> items = new ArrayList<CodeMapItem>(); // private ArrayList<CodeMapLink> links = new ArrayList<CodeMapLink>(); // private WorkspaceController controller; // // public WorkspaceView(Context context, AttributeSet attrs) { // super(context, attrs); // // this.scroller = new Scroller(getContext()); // this.gestureDetector = new GestureDetector(getContext(), new CodeMapGestureListener(this, scroller)); // this.scaleDetector = new ScaleGestureDetector(getContext(), new CodeMapScaleListener(this)); // // setWillNotDraw(false); // setFocusable(false); // } // // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // // canvas.save(); // canvas.scale(getScaleFactor(), getScaleFactor()); // // for(CodeMapLink link: links) // link.doDraw(canvas); // // canvas.restore(); // } // // public void refresh() { // invalidate(); // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // super.onTouchEvent(event); // // scaleDetector.onTouchEvent(event); // gestureDetector.onTouchEvent(event); // // updateScroll(); // return true; // } // // private void updateScroll() { // if(scroller.computeScrollOffset()) { // float dx = (scroller.getStartX() - scroller.getFinalX()); // float dy = (scroller.getStartY() - scroller.getFinalY()); // scrollBy(-(int)dx, -(int)dy); // } // } // // // public void addMapItem(CodeMapItem item) { // if (items.contains(item)) // return; // // addView(item); // items.add(item); // item.setCodeMapView(this); // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void addMapLink(CodeMapLink link) { // if(link.parent != null && link.child != null) { // links.add(link); // refresh(); // } // } // // public void remove(CodeMapItem item) { // removeView(item); // items.remove(item); // item.setCodeMapView(null); // // Iterator<CodeMapLink> linksIt = links.iterator(); // while(linksIt.hasNext()) { // CodeMapLink link = linksIt.next(); // if(link.hasItem(item)) // linksIt.remove(); // } // // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void clear() { // removeAllViews(); // items.clear(); // links.clear(); // } // // // public void moveFragment(CodeMapItem item, CodeMapPoint position) { // item.setPosition(position); // moveFragment(item); // } // // public void moveFragment(CodeMapItem item) { // CollisionManager.pushItems(item, this.items); // } // // public CodeMapItem getMapFragmentAtPoint(CodeMapCursorPoint cursorPoint) { // CodeMapPoint point = cursorPoint.getCodeMapPoint(this); // for (CodeMapItem view : items) { // if (view.contains(point)) // return view; // } // return null; // } // // // public void setController(WorkspaceController controller) { // this.controller = controller; // } // // public WorkspaceController getController() { // return this.controller; // } // // public WorkspaceState getState() { // WorkspaceState state = new WorkspaceState(controller.getWorkspaceName()); // // for(CodeMapItem item: items) // state.items.add(new SerializableItem(item)); // // for(CodeMapLink link: links) // state.links.add(new SerializableLink(link)); // // state.zoom = getScaleFactor(); // state.scrollX = getScrollX(); // state.scrollY = getScrollY(); // return state; // } // // // TODO Make more efficient // public ArrayList<CodeMapItem> getDeclarations(String url) { // ArrayList<CodeMapItem> result = new ArrayList<CodeMapItem>(); // Iterator<CodeMapItem> i = this.items.iterator(); // while (i.hasNext()) { // CodeMapItem item = i.next(); // // if (item.getUrl().equals(url)) // result.add(item); // } // // return result; // } // // public void setScroll(float x, float y) { // setScrollX((int) x); // setScrollY((int) y); // } // // public void setFontSize(int fontSize) { // for (CodeMapItem item: this.items) { // item.setFontSize(fontSize); // } // } // } // Path: src/com/hdweiss/codemap/util/ZoomableLinearLayout.java import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.view.ViewParent; import android.widget.LinearLayout; import com.hdweiss.codemap.view.workspace.WorkspaceView; package com.hdweiss.codemap.util; public class ZoomableLinearLayout extends LinearLayout { public ZoomableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public float getScaleFactor() {
return ((WorkspaceView) getParent()).getScaleFactor();
hdweiss/codemap
src/com/hdweiss/codemap/util/Utils.java
// Path: src/com/hdweiss/codemap/view/project/ProjectBrowser.java // public class SynchServiceReceiver extends BroadcastReceiver { // public static final String SYNC_UPDATE = "com.hdweiss.codemap.action.SYNC_UPDATE"; // // public static final String SYNC_NAME = "sync_name"; // public static final String SYNC_STATUS = "sync_status"; // public static final String SYNC_START = "sync_start"; // public static final String SYNC_DONE = "sync_done"; // public static final String SYNC_PROGRESS_UPDATE = "sync_update"; // // @Override // public void onReceive(Context context, Intent intent) { // boolean syncStart = intent.getBooleanExtra(SYNC_START, false); // boolean syncDone = intent.getBooleanExtra(SYNC_DONE, false); // int progress = intent.getIntExtra(SYNC_PROGRESS_UPDATE, -1); // // String status = intent.getStringExtra(SYNC_STATUS); // String projectName = intent.getStringExtra(SYNC_NAME); // int position = ((ProjectAdapter)listView.getAdapter()).getItemPosition(projectName); // ProjectItemView itemView = (ProjectItemView) listView.getChildAt(position); // // if (itemView == null) // return; // // if(syncStart) { // itemView.beginUpdate(); // } else if (syncDone) { // itemView.endUpdate(); // // } else { // if(progress > -1) // itemView.setProgress(progress); // itemView.setStatus(status); // } // } // }
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.TouchDelegate; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.hdweiss.codemap.view.project.ProjectBrowser.SynchServiceReceiver;
return null; } } public static void deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) deleteRecursive(child); fileOrDirectory.delete(); } public static void setupSpinner(Spinner spinner, ArrayList<String> data, String selection) { if(!TextUtils.isEmpty(selection) && !data.contains(selection)) data.add(selection); ArrayAdapter<String> adapter = new ArrayAdapter<String>(spinner.getContext(), android.R.layout.simple_spinner_item, data); spinner.setAdapter(adapter); int pos = data.indexOf(selection); if (pos < 0) { pos = 0; } spinner.setSelection(pos, true); } public static void announceSyncDone(Context context, String name) {
// Path: src/com/hdweiss/codemap/view/project/ProjectBrowser.java // public class SynchServiceReceiver extends BroadcastReceiver { // public static final String SYNC_UPDATE = "com.hdweiss.codemap.action.SYNC_UPDATE"; // // public static final String SYNC_NAME = "sync_name"; // public static final String SYNC_STATUS = "sync_status"; // public static final String SYNC_START = "sync_start"; // public static final String SYNC_DONE = "sync_done"; // public static final String SYNC_PROGRESS_UPDATE = "sync_update"; // // @Override // public void onReceive(Context context, Intent intent) { // boolean syncStart = intent.getBooleanExtra(SYNC_START, false); // boolean syncDone = intent.getBooleanExtra(SYNC_DONE, false); // int progress = intent.getIntExtra(SYNC_PROGRESS_UPDATE, -1); // // String status = intent.getStringExtra(SYNC_STATUS); // String projectName = intent.getStringExtra(SYNC_NAME); // int position = ((ProjectAdapter)listView.getAdapter()).getItemPosition(projectName); // ProjectItemView itemView = (ProjectItemView) listView.getChildAt(position); // // if (itemView == null) // return; // // if(syncStart) { // itemView.beginUpdate(); // } else if (syncDone) { // itemView.endUpdate(); // // } else { // if(progress > -1) // itemView.setProgress(progress); // itemView.setStatus(status); // } // } // } // Path: src/com/hdweiss/codemap/util/Utils.java import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.TouchDelegate; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.hdweiss.codemap.view.project.ProjectBrowser.SynchServiceReceiver; return null; } } public static void deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) deleteRecursive(child); fileOrDirectory.delete(); } public static void setupSpinner(Spinner spinner, ArrayList<String> data, String selection) { if(!TextUtils.isEmpty(selection) && !data.contains(selection)) data.add(selection); ArrayAdapter<String> adapter = new ArrayAdapter<String>(spinner.getContext(), android.R.layout.simple_spinner_item, data); spinner.setAdapter(adapter); int pos = data.indexOf(selection); if (pos < 0) { pos = 0; } spinner.setSelection(pos, true); } public static void announceSyncDone(Context context, String name) {
Intent intent = new Intent(SynchServiceReceiver.SYNC_UPDATE);
hdweiss/codemap
tests/src/com/hdweiss/codemap/test/CollisionManagerTest.java
// Path: src/com/hdweiss/codemap/view/workspace/CollisionManager.java // public class CollisionManager { // // private static final int padding = 5; // // public static boolean pushItems(CodeMapItem pushingItem, // ArrayList<CodeMapItem> items) { // Log.d("Collision", "-> pushItems(): " + pushingItem.getUrl()); // // for (CodeMapItem item : items) { // if (item == pushingItem) // continue; // // Point pushOffset = getPushOffset(pushingItem.getBounds(), // item.getBounds(), padding, true); // // if (pushOffset.equals(0, 0) == false) { // item.push(pushOffset); // Log.d("Collision", "pushItems(): pushed " + item.getUrl()); // fixPush(item, new ArrayList<CodeMapItem>(items), pushOffset); // } // } // // return true; // } // // private static void fixPush(CodeMapItem pushingItem, // ArrayList<CodeMapItem> items, Point pushOffset) { // items.remove(pushingItem); // Iterator<CodeMapItem> iterator = items.iterator(); // // while (iterator.hasNext()) { // CodeMapItem item; // try { // item = iterator.next(); // } catch (ConcurrentModificationException e) { // Log.e("Collision", "Collision manager caught ConcurrentModificationException"); // return; // } // if (pushingItem == item) // continue; // // if (Rect.intersects(pushingItem.getBounds(), item.getBounds())) { // Log.d("Collision", "fixPush(): " + pushingItem.getUrl() + " collided " + item.getUrl()); // item.push(pushOffset); // iterator.remove(); // fixPush(item, items, pushOffset); // } // } // } // // // public static Point getPushOffset(Rect pusher, Rect pushed) { // return getPushOffset(pusher, pushed, 0, true); // } // // public static Point getPushOffset(Rect pusher, Rect pushed, int padding, // boolean allowXPush) { // if (Rect.intersects(pusher, pushed) == false) // return new Point(0, 0); // // int pushUp = Math.abs(pusher.top - pushed.bottom); // int pushDown = Math.abs(pusher.bottom - pushed.top); // int pushRight = Math.abs(pusher.right - pushed.left); // int pushLeft = Math.abs(pusher.left - pushed.right); // // int pushX; // int pushY; // // if (pushUp < pushDown) // pushY = -pushUp; // else // pushY = pushDown; // // if (pushLeft < pushRight) // pushX = -pushLeft; // else // pushX = pushRight; // // if (pushX == 0 && pushY == 0) // return new Point(0, 0); // // if (allowXPush && Math.abs(pushX) < Math.abs(pushY)) // return new Point(pushX + padding, 0); // else // return new Point(0, pushY + padding); // } // // }
import android.graphics.Point; import android.graphics.Rect; import android.test.AndroidTestCase; import com.hdweiss.codemap.view.workspace.CollisionManager;
package com.hdweiss.codemap.test; public class CollisionManagerTest extends AndroidTestCase { public void test_getPushOffset_nonOverlap() { Rect rect1 = new Rect(100, 100, 200, 200); Rect rect2 = new Rect(300, 300, 400, 400);
// Path: src/com/hdweiss/codemap/view/workspace/CollisionManager.java // public class CollisionManager { // // private static final int padding = 5; // // public static boolean pushItems(CodeMapItem pushingItem, // ArrayList<CodeMapItem> items) { // Log.d("Collision", "-> pushItems(): " + pushingItem.getUrl()); // // for (CodeMapItem item : items) { // if (item == pushingItem) // continue; // // Point pushOffset = getPushOffset(pushingItem.getBounds(), // item.getBounds(), padding, true); // // if (pushOffset.equals(0, 0) == false) { // item.push(pushOffset); // Log.d("Collision", "pushItems(): pushed " + item.getUrl()); // fixPush(item, new ArrayList<CodeMapItem>(items), pushOffset); // } // } // // return true; // } // // private static void fixPush(CodeMapItem pushingItem, // ArrayList<CodeMapItem> items, Point pushOffset) { // items.remove(pushingItem); // Iterator<CodeMapItem> iterator = items.iterator(); // // while (iterator.hasNext()) { // CodeMapItem item; // try { // item = iterator.next(); // } catch (ConcurrentModificationException e) { // Log.e("Collision", "Collision manager caught ConcurrentModificationException"); // return; // } // if (pushingItem == item) // continue; // // if (Rect.intersects(pushingItem.getBounds(), item.getBounds())) { // Log.d("Collision", "fixPush(): " + pushingItem.getUrl() + " collided " + item.getUrl()); // item.push(pushOffset); // iterator.remove(); // fixPush(item, items, pushOffset); // } // } // } // // // public static Point getPushOffset(Rect pusher, Rect pushed) { // return getPushOffset(pusher, pushed, 0, true); // } // // public static Point getPushOffset(Rect pusher, Rect pushed, int padding, // boolean allowXPush) { // if (Rect.intersects(pusher, pushed) == false) // return new Point(0, 0); // // int pushUp = Math.abs(pusher.top - pushed.bottom); // int pushDown = Math.abs(pusher.bottom - pushed.top); // int pushRight = Math.abs(pusher.right - pushed.left); // int pushLeft = Math.abs(pusher.left - pushed.right); // // int pushX; // int pushY; // // if (pushUp < pushDown) // pushY = -pushUp; // else // pushY = pushDown; // // if (pushLeft < pushRight) // pushX = -pushLeft; // else // pushX = pushRight; // // if (pushX == 0 && pushY == 0) // return new Point(0, 0); // // if (allowXPush && Math.abs(pushX) < Math.abs(pushY)) // return new Point(pushX + padding, 0); // else // return new Point(0, pushY + padding); // } // // } // Path: tests/src/com/hdweiss/codemap/test/CollisionManagerTest.java import android.graphics.Point; import android.graphics.Rect; import android.test.AndroidTestCase; import com.hdweiss.codemap.view.workspace.CollisionManager; package com.hdweiss.codemap.test; public class CollisionManagerTest extends AndroidTestCase { public void test_getPushOffset_nonOverlap() { Rect rect1 = new Rect(100, 100, 200, 200); Rect rect2 = new Rect(300, 300, 400, 400);
Point pushOffset = CollisionManager.getPushOffset(rect1, rect2);
hdweiss/codemap
src/com/hdweiss/codemap/view/workspace/outline/OutlineItemView.java
// Path: src/com/hdweiss/codemap/view/workspace/outline/OutlineItem.java // public enum TYPE {DIRECTORY, FILE, SYMBOL};
import android.content.Context; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.TextView; import com.hdweiss.codemap.R; import com.hdweiss.codemap.R.color; import com.hdweiss.codemap.view.workspace.outline.OutlineItem.TYPE;
package com.hdweiss.codemap.view.workspace.outline; public class OutlineItemView extends LinearLayout { private TextView textView; private TextView declarationView; public OutlineItemView(Context context) { super(context); LayoutInflater.from(context).inflate(R.layout.outline_item, this); this.textView = (TextView) findViewById(R.id.browser_item); this.declarationView = (TextView) findViewById(R.id.browser_declare); } public void setItem(OutlineItem item) { String text = item.name;
// Path: src/com/hdweiss/codemap/view/workspace/outline/OutlineItem.java // public enum TYPE {DIRECTORY, FILE, SYMBOL}; // Path: src/com/hdweiss/codemap/view/workspace/outline/OutlineItemView.java import android.content.Context; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.TextView; import com.hdweiss.codemap.R; import com.hdweiss.codemap.R.color; import com.hdweiss.codemap.view.workspace.outline.OutlineItem.TYPE; package com.hdweiss.codemap.view.workspace.outline; public class OutlineItemView extends LinearLayout { private TextView textView; private TextView declarationView; public OutlineItemView(Context context) { super(context); LayoutInflater.from(context).inflate(R.layout.outline_item, this); this.textView = (TextView) findViewById(R.id.browser_item); this.declarationView = (TextView) findViewById(R.id.browser_declare); } public void setItem(OutlineItem item) { String text = item.name;
if(item.type == TYPE.FILE) {
hdweiss/codemap
src/com/hdweiss/codemap/view/workspace/fragments/FunctionLinkSpan.java
// Path: src/com/hdweiss/codemap/util/SpanUtils.java // public interface SpanConverter<A extends CharacterStyle, B extends CharacterStyle> { // B convert(A span); // }
import android.text.style.ClickableSpan; import android.text.style.URLSpan; import android.view.View; import com.hdweiss.codemap.util.SpanUtils.SpanConverter;
package com.hdweiss.codemap.view.workspace.fragments; public class FunctionLinkSpan extends ClickableSpan { private CodeMapFunction codeMapFunction; private String url; public FunctionLinkSpan(CodeMapFunction codeMapFunction, String url) { this.codeMapFunction = codeMapFunction; this.url = url; } @Override public void onClick(View widget) { codeMapFunction.addChildFragment(url); } public static class FunctionLinkSpanConverter implements
// Path: src/com/hdweiss/codemap/util/SpanUtils.java // public interface SpanConverter<A extends CharacterStyle, B extends CharacterStyle> { // B convert(A span); // } // Path: src/com/hdweiss/codemap/view/workspace/fragments/FunctionLinkSpan.java import android.text.style.ClickableSpan; import android.text.style.URLSpan; import android.view.View; import com.hdweiss.codemap.util.SpanUtils.SpanConverter; package com.hdweiss.codemap.view.workspace.fragments; public class FunctionLinkSpan extends ClickableSpan { private CodeMapFunction codeMapFunction; private String url; public FunctionLinkSpan(CodeMapFunction codeMapFunction, String url) { this.codeMapFunction = codeMapFunction; this.url = url; } @Override public void onClick(View widget) { codeMapFunction.addChildFragment(url); } public static class FunctionLinkSpanConverter implements
SpanConverter<URLSpan, FunctionLinkSpan> {
hdweiss/codemap
src/com/hdweiss/codemap/util/CodeMapCursorPoint.java
// Path: src/com/hdweiss/codemap/view/workspace/WorkspaceView.java // public class WorkspaceView extends ZoomableAbsoluteLayout { // // private GestureDetector gestureDetector; // private ScaleGestureDetector scaleDetector; // private Scroller scroller; // // public ArrayList<CodeMapItem> items = new ArrayList<CodeMapItem>(); // private ArrayList<CodeMapLink> links = new ArrayList<CodeMapLink>(); // private WorkspaceController controller; // // public WorkspaceView(Context context, AttributeSet attrs) { // super(context, attrs); // // this.scroller = new Scroller(getContext()); // this.gestureDetector = new GestureDetector(getContext(), new CodeMapGestureListener(this, scroller)); // this.scaleDetector = new ScaleGestureDetector(getContext(), new CodeMapScaleListener(this)); // // setWillNotDraw(false); // setFocusable(false); // } // // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // // canvas.save(); // canvas.scale(getScaleFactor(), getScaleFactor()); // // for(CodeMapLink link: links) // link.doDraw(canvas); // // canvas.restore(); // } // // public void refresh() { // invalidate(); // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // super.onTouchEvent(event); // // scaleDetector.onTouchEvent(event); // gestureDetector.onTouchEvent(event); // // updateScroll(); // return true; // } // // private void updateScroll() { // if(scroller.computeScrollOffset()) { // float dx = (scroller.getStartX() - scroller.getFinalX()); // float dy = (scroller.getStartY() - scroller.getFinalY()); // scrollBy(-(int)dx, -(int)dy); // } // } // // // public void addMapItem(CodeMapItem item) { // if (items.contains(item)) // return; // // addView(item); // items.add(item); // item.setCodeMapView(this); // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void addMapLink(CodeMapLink link) { // if(link.parent != null && link.child != null) { // links.add(link); // refresh(); // } // } // // public void remove(CodeMapItem item) { // removeView(item); // items.remove(item); // item.setCodeMapView(null); // // Iterator<CodeMapLink> linksIt = links.iterator(); // while(linksIt.hasNext()) { // CodeMapLink link = linksIt.next(); // if(link.hasItem(item)) // linksIt.remove(); // } // // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void clear() { // removeAllViews(); // items.clear(); // links.clear(); // } // // // public void moveFragment(CodeMapItem item, CodeMapPoint position) { // item.setPosition(position); // moveFragment(item); // } // // public void moveFragment(CodeMapItem item) { // CollisionManager.pushItems(item, this.items); // } // // public CodeMapItem getMapFragmentAtPoint(CodeMapCursorPoint cursorPoint) { // CodeMapPoint point = cursorPoint.getCodeMapPoint(this); // for (CodeMapItem view : items) { // if (view.contains(point)) // return view; // } // return null; // } // // // public void setController(WorkspaceController controller) { // this.controller = controller; // } // // public WorkspaceController getController() { // return this.controller; // } // // public WorkspaceState getState() { // WorkspaceState state = new WorkspaceState(controller.getWorkspaceName()); // // for(CodeMapItem item: items) // state.items.add(new SerializableItem(item)); // // for(CodeMapLink link: links) // state.links.add(new SerializableLink(link)); // // state.zoom = getScaleFactor(); // state.scrollX = getScrollX(); // state.scrollY = getScrollY(); // return state; // } // // // TODO Make more efficient // public ArrayList<CodeMapItem> getDeclarations(String url) { // ArrayList<CodeMapItem> result = new ArrayList<CodeMapItem>(); // Iterator<CodeMapItem> i = this.items.iterator(); // while (i.hasNext()) { // CodeMapItem item = i.next(); // // if (item.getUrl().equals(url)) // result.add(item); // } // // return result; // } // // public void setScroll(float x, float y) { // setScrollX((int) x); // setScrollY((int) y); // } // // public void setFontSize(int fontSize) { // for (CodeMapItem item: this.items) { // item.setFontSize(fontSize); // } // } // }
import com.hdweiss.codemap.view.workspace.WorkspaceView; import android.graphics.PointF;
package com.hdweiss.codemap.util; /** * Wrapper for points that are clicked on canvas. */ public class CodeMapCursorPoint extends PointF { public CodeMapCursorPoint() { super(); } public CodeMapCursorPoint(float x, float y) { super(x, y); }
// Path: src/com/hdweiss/codemap/view/workspace/WorkspaceView.java // public class WorkspaceView extends ZoomableAbsoluteLayout { // // private GestureDetector gestureDetector; // private ScaleGestureDetector scaleDetector; // private Scroller scroller; // // public ArrayList<CodeMapItem> items = new ArrayList<CodeMapItem>(); // private ArrayList<CodeMapLink> links = new ArrayList<CodeMapLink>(); // private WorkspaceController controller; // // public WorkspaceView(Context context, AttributeSet attrs) { // super(context, attrs); // // this.scroller = new Scroller(getContext()); // this.gestureDetector = new GestureDetector(getContext(), new CodeMapGestureListener(this, scroller)); // this.scaleDetector = new ScaleGestureDetector(getContext(), new CodeMapScaleListener(this)); // // setWillNotDraw(false); // setFocusable(false); // } // // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // // canvas.save(); // canvas.scale(getScaleFactor(), getScaleFactor()); // // for(CodeMapLink link: links) // link.doDraw(canvas); // // canvas.restore(); // } // // public void refresh() { // invalidate(); // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // super.onTouchEvent(event); // // scaleDetector.onTouchEvent(event); // gestureDetector.onTouchEvent(event); // // updateScroll(); // return true; // } // // private void updateScroll() { // if(scroller.computeScrollOffset()) { // float dx = (scroller.getStartX() - scroller.getFinalX()); // float dy = (scroller.getStartY() - scroller.getFinalY()); // scrollBy(-(int)dx, -(int)dy); // } // } // // // public void addMapItem(CodeMapItem item) { // if (items.contains(item)) // return; // // addView(item); // items.add(item); // item.setCodeMapView(this); // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void addMapLink(CodeMapLink link) { // if(link.parent != null && link.child != null) { // links.add(link); // refresh(); // } // } // // public void remove(CodeMapItem item) { // removeView(item); // items.remove(item); // item.setCodeMapView(null); // // Iterator<CodeMapLink> linksIt = links.iterator(); // while(linksIt.hasNext()) { // CodeMapLink link = linksIt.next(); // if(link.hasItem(item)) // linksIt.remove(); // } // // controller.updateCodeBrowser(); // controller.updateWorkspaceBrowser(); // } // // public void clear() { // removeAllViews(); // items.clear(); // links.clear(); // } // // // public void moveFragment(CodeMapItem item, CodeMapPoint position) { // item.setPosition(position); // moveFragment(item); // } // // public void moveFragment(CodeMapItem item) { // CollisionManager.pushItems(item, this.items); // } // // public CodeMapItem getMapFragmentAtPoint(CodeMapCursorPoint cursorPoint) { // CodeMapPoint point = cursorPoint.getCodeMapPoint(this); // for (CodeMapItem view : items) { // if (view.contains(point)) // return view; // } // return null; // } // // // public void setController(WorkspaceController controller) { // this.controller = controller; // } // // public WorkspaceController getController() { // return this.controller; // } // // public WorkspaceState getState() { // WorkspaceState state = new WorkspaceState(controller.getWorkspaceName()); // // for(CodeMapItem item: items) // state.items.add(new SerializableItem(item)); // // for(CodeMapLink link: links) // state.links.add(new SerializableLink(link)); // // state.zoom = getScaleFactor(); // state.scrollX = getScrollX(); // state.scrollY = getScrollY(); // return state; // } // // // TODO Make more efficient // public ArrayList<CodeMapItem> getDeclarations(String url) { // ArrayList<CodeMapItem> result = new ArrayList<CodeMapItem>(); // Iterator<CodeMapItem> i = this.items.iterator(); // while (i.hasNext()) { // CodeMapItem item = i.next(); // // if (item.getUrl().equals(url)) // result.add(item); // } // // return result; // } // // public void setScroll(float x, float y) { // setScrollX((int) x); // setScrollY((int) y); // } // // public void setFontSize(int fontSize) { // for (CodeMapItem item: this.items) { // item.setFontSize(fontSize); // } // } // } // Path: src/com/hdweiss/codemap/util/CodeMapCursorPoint.java import com.hdweiss.codemap.view.workspace.WorkspaceView; import android.graphics.PointF; package com.hdweiss.codemap.util; /** * Wrapper for points that are clicked on canvas. */ public class CodeMapCursorPoint extends PointF { public CodeMapCursorPoint() { super(); } public CodeMapCursorPoint(float x, float y) { super(x, y); }
public CodeMapPoint getCodeMapPoint(WorkspaceView codeMapView) {
hdweiss/codemap
src/com/hdweiss/codemap/util/SyntaxHighlighter.java
// Path: src/com/hdweiss/codemap/data/CscopeEntry.java // public class CscopeEntry { // private static int CSCOPE_FILE = 1; // private static int CSCOPE_ACTUALNAME = 2; // private static int CSCOPE_NAME = 4; // private static int CSCOPE_LINENUMBER = 3; // // public String actualName = ""; // public String name = ""; // public String file = ""; // public int lineNumber = -1; // private int endLine = -2; // // private static Pattern CscopeEntryPattern = Pattern.compile("(\\S*)\\s(\\S*)\\s(\\d*)\\s(.*)"); // public CscopeEntry(String line) { // Matcher matcher = CscopeEntryPattern.matcher(line); // // if(matcher.find()) { // this.file = matcher.group(CSCOPE_FILE); // this.name = matcher.group(CSCOPE_NAME); // this.actualName = matcher.group(CSCOPE_ACTUALNAME); // this.lineNumber = Integer.parseInt(matcher.group(CSCOPE_LINENUMBER)); // } else // throw new IllegalArgumentException("Couldn't parse " + line); // } // // public int getEndLine(CscopeWrapper cscopeWrapper) { // if (endLine == -2) // endLine = cscopeWrapper.getFunctionEndLine(this); // return endLine; // } // // public String getUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + name; // } else // return file + ":" + name; // } // // public String getActualUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + actualName; // } else // return file + ":" + actualName; // } // // public String toString() { // return file + ":" + name + "@" + lineNumber; // } // }
import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.Html; import android.text.SpannableString; import com.hdweiss.codemap.data.CscopeEntry;
this.content = contents; } public SpannableString formatToHtml() { formatNewline(); highlightKeywords(); highlightComments(); SpannableString spannableString = new SpannableString( Html.fromHtml(content)); return spannableString; } private void formatNewline() { content = content.replaceAll("\n\r", "<br />"); content = content.replaceAll("\n", "<br />"); content = content.replaceAll("\r", "<br />"); } private void highlightKeywords() { for(String keyword: C_KEYWORDS) { content = content.replaceAll(keyword, "<font color=\"purple\">" + keyword + "</font>"); } } private void highlightComments() { content = content.replaceAll("/\\*.*?\\*/", "<font color=\"green\">$0</font>"); content = content.replaceAll("//[^\n]*?\n", "<font color=\"green\">$0</font>"); }
// Path: src/com/hdweiss/codemap/data/CscopeEntry.java // public class CscopeEntry { // private static int CSCOPE_FILE = 1; // private static int CSCOPE_ACTUALNAME = 2; // private static int CSCOPE_NAME = 4; // private static int CSCOPE_LINENUMBER = 3; // // public String actualName = ""; // public String name = ""; // public String file = ""; // public int lineNumber = -1; // private int endLine = -2; // // private static Pattern CscopeEntryPattern = Pattern.compile("(\\S*)\\s(\\S*)\\s(\\d*)\\s(.*)"); // public CscopeEntry(String line) { // Matcher matcher = CscopeEntryPattern.matcher(line); // // if(matcher.find()) { // this.file = matcher.group(CSCOPE_FILE); // this.name = matcher.group(CSCOPE_NAME); // this.actualName = matcher.group(CSCOPE_ACTUALNAME); // this.lineNumber = Integer.parseInt(matcher.group(CSCOPE_LINENUMBER)); // } else // throw new IllegalArgumentException("Couldn't parse " + line); // } // // public int getEndLine(CscopeWrapper cscopeWrapper) { // if (endLine == -2) // endLine = cscopeWrapper.getFunctionEndLine(this); // return endLine; // } // // public String getUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + name; // } else // return file + ":" + name; // } // // public String getActualUrl(String projectPath) { // if (file.length() > projectPath.length()) { // String relativeFilename = file.substring(projectPath.length() + 1); // return relativeFilename + ":" + actualName; // } else // return file + ":" + actualName; // } // // public String toString() { // return file + ":" + name + "@" + lineNumber; // } // } // Path: src/com/hdweiss/codemap/util/SyntaxHighlighter.java import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.Html; import android.text.SpannableString; import com.hdweiss.codemap.data.CscopeEntry; this.content = contents; } public SpannableString formatToHtml() { formatNewline(); highlightKeywords(); highlightComments(); SpannableString spannableString = new SpannableString( Html.fromHtml(content)); return spannableString; } private void formatNewline() { content = content.replaceAll("\n\r", "<br />"); content = content.replaceAll("\n", "<br />"); content = content.replaceAll("\r", "<br />"); } private void highlightKeywords() { for(String keyword: C_KEYWORDS) { content = content.replaceAll(keyword, "<font color=\"purple\">" + keyword + "</font>"); } } private void highlightComments() { content = content.replaceAll("/\\*.*?\\*/", "<font color=\"green\">$0</font>"); content = content.replaceAll("//[^\n]*?\n", "<font color=\"green\">$0</font>"); }
public void markupReferences(ArrayList<CscopeEntry> references) {
hdweiss/codemap
src/com/hdweiss/codemap/view/workspace/CollisionManager.java
// Path: src/com/hdweiss/codemap/view/workspace/fragments/CodeMapItem.java // public abstract class CodeMapItem extends LinearLayout implements ICodeMapItem { // public UUID id = UUID.randomUUID(); // // public TextView titleView; // private ImageButton removeButton; // private LinearLayout containerView; // // private View contentView; // protected WorkspaceView codeMapView; // // private boolean moveItem = false; // // public CodeMapItem(Context context, AttributeSet attrs, String name) { // super(context, attrs); // // inflate(context, R.layout.codemap_item, this); // // containerView = (LinearLayout) findViewById(R.id.codemap_item_container); // // titleView = (TextView) findViewById(R.id.title); // titleView.setText(name); // // removeButton = (ImageButton) findViewById(R.id.remove); // removeButton.setOnClickListener(new OnClickListener() { // public void onClick(View v) { // remove(); // } // }); // // this.post(Utils.getTouchDelegateAction(this, removeButton, 50, 50, 50, 50)); // } // // // public void setCodeMapView(WorkspaceView codeMapView) { // this.codeMapView = codeMapView; // } // // // @Override // protected void onSizeChanged(int w, int h, int oldw, int oldh) { // super.onSizeChanged(w, h, oldw, oldh); // // if (this.codeMapView != null && moveItem) { // this.codeMapView.moveFragment(this); // this.moveItem = false; // } // } // // protected void setContentView(View view) { // this.contentView = view; // containerView.addView(view); // } // // // public void setPosition(CodeMapPoint point) { // setX(point.x); // setY(point.y); // } // // public CodeMapPoint getPosition() { // return new CodeMapPoint(getX(), getY()); // } // // public void setPositionCenter(CodeMapPoint point) { // float startX = point.x - (getWidth() / 2); // float startY = point.y - (getHeight() / 2); // setX(startX); // setY(startY); // } // // public Rect getBounds() { // final int top = (int) getY(); // final int bottom = top + getHeight(); // // final int left = (int) getX(); // final int right = left + getWidth(); // // return new Rect(left, top, right, bottom); // } // // public void push(Point offset) { // setX(getX() + offset.x); // setY(getY() + offset.y); // } // // public boolean contains(CodeMapPoint point) { // // Log.d("CodeMap", "point : [" + getX() + " < " + point.x + " < " // // + (getX() + getWidth()) + "] [" + getY() + " < " + point.y // // + " < " + (getY() + getHeight()) + "]"); // if (point.x >= getX() && point.x <= getX() + getWidth() // && point.y >= getY() && point.y <= getY() + getHeight()) { // //Log.d("CodeMap", "match!"); // return true; // } // else // return false; // } // // public void makeItemMoveable() { // this.moveItem = true; // } // // public void remove() { // if(codeMapView != null) // codeMapView.remove(this); // } // // public String getUrl() { // return this.titleView.getText().toString(); // } // // public float getContentViewYOffset() { // return titleView.getHeight() + titleView.getPaddingTop() // + titleView.getPaddingBottom() + contentView.getPaddingTop() // + contentView.getPaddingBottom() + 5; // } // // public float getTitleViewYMid() { // return this.getY() + (titleView.getHeight() / 2); // } // // public void setFontSize(int fontSize) { // // Do nothing // } // // public void setupForAnnotation() { // containerView.setBackgroundResource(R.drawable.fragment_bg_annotation); // } // }
import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Iterator; import android.graphics.Point; import android.graphics.Rect; import android.util.Log; import com.hdweiss.codemap.view.workspace.fragments.CodeMapItem;
package com.hdweiss.codemap.view.workspace; public class CollisionManager { private static final int padding = 5;
// Path: src/com/hdweiss/codemap/view/workspace/fragments/CodeMapItem.java // public abstract class CodeMapItem extends LinearLayout implements ICodeMapItem { // public UUID id = UUID.randomUUID(); // // public TextView titleView; // private ImageButton removeButton; // private LinearLayout containerView; // // private View contentView; // protected WorkspaceView codeMapView; // // private boolean moveItem = false; // // public CodeMapItem(Context context, AttributeSet attrs, String name) { // super(context, attrs); // // inflate(context, R.layout.codemap_item, this); // // containerView = (LinearLayout) findViewById(R.id.codemap_item_container); // // titleView = (TextView) findViewById(R.id.title); // titleView.setText(name); // // removeButton = (ImageButton) findViewById(R.id.remove); // removeButton.setOnClickListener(new OnClickListener() { // public void onClick(View v) { // remove(); // } // }); // // this.post(Utils.getTouchDelegateAction(this, removeButton, 50, 50, 50, 50)); // } // // // public void setCodeMapView(WorkspaceView codeMapView) { // this.codeMapView = codeMapView; // } // // // @Override // protected void onSizeChanged(int w, int h, int oldw, int oldh) { // super.onSizeChanged(w, h, oldw, oldh); // // if (this.codeMapView != null && moveItem) { // this.codeMapView.moveFragment(this); // this.moveItem = false; // } // } // // protected void setContentView(View view) { // this.contentView = view; // containerView.addView(view); // } // // // public void setPosition(CodeMapPoint point) { // setX(point.x); // setY(point.y); // } // // public CodeMapPoint getPosition() { // return new CodeMapPoint(getX(), getY()); // } // // public void setPositionCenter(CodeMapPoint point) { // float startX = point.x - (getWidth() / 2); // float startY = point.y - (getHeight() / 2); // setX(startX); // setY(startY); // } // // public Rect getBounds() { // final int top = (int) getY(); // final int bottom = top + getHeight(); // // final int left = (int) getX(); // final int right = left + getWidth(); // // return new Rect(left, top, right, bottom); // } // // public void push(Point offset) { // setX(getX() + offset.x); // setY(getY() + offset.y); // } // // public boolean contains(CodeMapPoint point) { // // Log.d("CodeMap", "point : [" + getX() + " < " + point.x + " < " // // + (getX() + getWidth()) + "] [" + getY() + " < " + point.y // // + " < " + (getY() + getHeight()) + "]"); // if (point.x >= getX() && point.x <= getX() + getWidth() // && point.y >= getY() && point.y <= getY() + getHeight()) { // //Log.d("CodeMap", "match!"); // return true; // } // else // return false; // } // // public void makeItemMoveable() { // this.moveItem = true; // } // // public void remove() { // if(codeMapView != null) // codeMapView.remove(this); // } // // public String getUrl() { // return this.titleView.getText().toString(); // } // // public float getContentViewYOffset() { // return titleView.getHeight() + titleView.getPaddingTop() // + titleView.getPaddingBottom() + contentView.getPaddingTop() // + contentView.getPaddingBottom() + 5; // } // // public float getTitleViewYMid() { // return this.getY() + (titleView.getHeight() / 2); // } // // public void setFontSize(int fontSize) { // // Do nothing // } // // public void setupForAnnotation() { // containerView.setBackgroundResource(R.drawable.fragment_bg_annotation); // } // } // Path: src/com/hdweiss/codemap/view/workspace/CollisionManager.java import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Iterator; import android.graphics.Point; import android.graphics.Rect; import android.util.Log; import com.hdweiss.codemap.view.workspace.fragments.CodeMapItem; package com.hdweiss.codemap.view.workspace; public class CollisionManager { private static final int padding = 5;
public static boolean pushItems(CodeMapItem pushingItem,
ntmcminn/CounterSign
countersign-repo/src/main/java/org/alfresco/extension/countersign/signature/RepositoryManagedSignatureProviderFactory.java
// Path: countersign-repo/src/main/java/org/alfresco/extension/countersign/service/CounterSignService.java // public interface CounterSignService { // public NodeRef getSignatureArtifact(String person, QName assoc); // public NodeRef getSignatureArtifact(NodeRef person, QName assoc); // }
import org.alfresco.extension.countersign.service.CounterSignService; import org.alfresco.service.ServiceRegistry; import java.util.Properties;
/* * Copyright 2012-2013 Alfresco Software Limited. * * Licensed under the GNU Affero General Public License, Version 3.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.gnu.org/licenses/agpl-3.0.html * * If you do not wish to be bound to the terms of the AGPL v3.0, * A commercial license may be obtained by contacting the author. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of an unsupported extension to Alfresco. * */ package org.alfresco.extension.countersign.signature; public class RepositoryManagedSignatureProviderFactory implements SignatureProviderFactory { private ServiceRegistry serviceRegistry;
// Path: countersign-repo/src/main/java/org/alfresco/extension/countersign/service/CounterSignService.java // public interface CounterSignService { // public NodeRef getSignatureArtifact(String person, QName assoc); // public NodeRef getSignatureArtifact(NodeRef person, QName assoc); // } // Path: countersign-repo/src/main/java/org/alfresco/extension/countersign/signature/RepositoryManagedSignatureProviderFactory.java import org.alfresco.extension.countersign.service.CounterSignService; import org.alfresco.service.ServiceRegistry; import java.util.Properties; /* * Copyright 2012-2013 Alfresco Software Limited. * * Licensed under the GNU Affero General Public License, Version 3.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.gnu.org/licenses/agpl-3.0.html * * If you do not wish to be bound to the terms of the AGPL v3.0, * A commercial license may be obtained by contacting the author. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of an unsupported extension to Alfresco. * */ package org.alfresco.extension.countersign.signature; public class RepositoryManagedSignatureProviderFactory implements SignatureProviderFactory { private ServiceRegistry serviceRegistry;
private CounterSignService counterSignService;
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/game/Board.java
// Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // // Path: core/src/dev/lonami/klooni/serializer/BinSerializable.java // public interface BinSerializable { // void write(final DataOutputStream out) throws IOException; // // void read(final DataInputStream in) throws IOException; // }
import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; import dev.lonami.klooni.serializer.BinSerializable;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.game; // Represents the on screen board, with all the put cells // and functions to determine when it is game over given a PieceHolder public class Board implements BinSerializable { //region Members public final int cellCount; public float cellSize; private Cell[][] cells;
// Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // // Path: core/src/dev/lonami/klooni/serializer/BinSerializable.java // public interface BinSerializable { // void write(final DataOutputStream out) throws IOException; // // void read(final DataInputStream in) throws IOException; // } // Path: core/src/dev/lonami/klooni/game/Board.java import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; import dev.lonami.klooni.serializer.BinSerializable; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.game; // Represents the on screen board, with all the put cells // and functions to determine when it is game over given a PieceHolder public class Board implements BinSerializable { //region Members public final int cellCount; public float cellSize; private Cell[][] cells;
private final Array<IEffect> effects = new Array<IEffect>(); // Particle effects once they vanish
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/game/Board.java
// Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // // Path: core/src/dev/lonami/klooni/serializer/BinSerializable.java // public interface BinSerializable { // void write(final DataOutputStream out) throws IOException; // // void read(final DataInputStream in) throws IOException; // }
import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; import dev.lonami.klooni.serializer.BinSerializable;
return putPiece(piece, x, y); } Vector2 snapToGrid(final Piece piece, final Vector2 position) { // Snaps the given position (e.g. mouse) to the grid, // assuming piece wants to be put at the specified position. // If the piece was not on the grid, the original position is returned // // Logic to determine the x and y is a copy-paste from putScreenPiece final Vector2 local = position.cpy().sub(pos); int x = MathUtils.round(local.x / piece.cellSize); int y = MathUtils.round(local.y / piece.cellSize); if (canPutPiece(piece, x, y)) return new Vector2(pos.x + x * piece.cellSize, pos.y + y * piece.cellSize); else return position; } // This will clear both complete rows and columns, all at once. // The reason why we can't check first rows and then columns // (or vice versa) is because the following case (* filled, _ empty): // // 4x4 boardHeight piece // _ _ * * * * // _ * * * * // * * _ _ // * * _ _ // // If the piece is put on the top left corner, all the cells will be cleared. // If we first cleared the columns, then the rows wouldn't have been cleared.
// Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // // Path: core/src/dev/lonami/klooni/serializer/BinSerializable.java // public interface BinSerializable { // void write(final DataOutputStream out) throws IOException; // // void read(final DataInputStream in) throws IOException; // } // Path: core/src/dev/lonami/klooni/game/Board.java import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; import dev.lonami.klooni.serializer.BinSerializable; return putPiece(piece, x, y); } Vector2 snapToGrid(final Piece piece, final Vector2 position) { // Snaps the given position (e.g. mouse) to the grid, // assuming piece wants to be put at the specified position. // If the piece was not on the grid, the original position is returned // // Logic to determine the x and y is a copy-paste from putScreenPiece final Vector2 local = position.cpy().sub(pos); int x = MathUtils.round(local.x / piece.cellSize); int y = MathUtils.round(local.y / piece.cellSize); if (canPutPiece(piece, x, y)) return new Vector2(pos.x + x * piece.cellSize, pos.y + y * piece.cellSize); else return position; } // This will clear both complete rows and columns, all at once. // The reason why we can't check first rows and then columns // (or vice versa) is because the following case (* filled, _ empty): // // 4x4 boardHeight piece // _ _ * * * * // _ * * * * // * * _ _ // * * _ _ // // If the piece is put on the top left corner, all the cells will be cleared. // If we first cleared the columns, then the rows wouldn't have been cleared.
public int clearComplete(final IEffectFactory effect) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/EvaporateEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class EvaporateEffectFactory implements IEffectFactory { @Override public String getName() { return "evaporate"; } @Override public String getDisplay() { return "Evaporate"; } @Override public int getPrice() { return 200; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/EvaporateEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class EvaporateEffectFactory implements IEffectFactory { @Override public String getName() { return "evaporate"; } @Override public String getDisplay() { return "Evaporate"; } @Override public int getPrice() { return 200; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/EvaporateEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class EvaporateEffectFactory implements IEffectFactory { @Override public String getName() { return "evaporate"; } @Override public String getDisplay() { return "Evaporate"; } @Override public int getPrice() { return 200; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/EvaporateEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class EvaporateEffectFactory implements IEffectFactory { @Override public String getName() { return "evaporate"; } @Override public String getDisplay() { return "Evaporate"; } @Override public int getPrice() { return 200; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/SpinEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class SpinEffectFactory implements IEffectFactory { @Override public String getName() { return "spin"; } @Override public String getDisplay() { return "Spin"; } @Override public int getPrice() { return 200; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/SpinEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class SpinEffectFactory implements IEffectFactory { @Override public String getName() { return "spin"; } @Override public String getDisplay() { return "Spin"; } @Override public int getPrice() { return 200; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/SpinEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class SpinEffectFactory implements IEffectFactory { @Override public String getName() { return "spin"; } @Override public String getDisplay() { return "Spin"; } @Override public int getPrice() { return 200; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/SpinEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class SpinEffectFactory implements IEffectFactory { @Override public String getName() { return "spin"; } @Override public String getDisplay() { return "Spin"; } @Override public int getPrice() { return 200; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/VanishEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class VanishEffectFactory implements IEffectFactory { @Override public String getName() { return "vanish"; } @Override public String getDisplay() { return "Vanish"; } @Override public int getPrice() { return 0; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/VanishEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class VanishEffectFactory implements IEffectFactory { @Override public String getName() { return "vanish"; } @Override public String getDisplay() { return "Vanish"; } @Override public int getPrice() { return 0; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/VanishEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class VanishEffectFactory implements IEffectFactory { @Override public String getName() { return "vanish"; } @Override public String getDisplay() { return "Vanish"; } @Override public int getPrice() { return 0; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/VanishEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class VanishEffectFactory implements IEffectFactory { @Override public String getName() { return "vanish"; } @Override public String getDisplay() { return "Vanish"; } @Override public int getPrice() { return 0; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/interfaces/IEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // }
import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.interfaces; /** * IEffectFactory interface has to be implemented for each effect. * <p> * It tells the name and the price of the effect and will create it, when needed. * * @see IEffect */ public interface IEffectFactory { String getName(); String getDisplay(); int getPrice();
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java import com.badlogic.gdx.math.Vector2; import dev.lonami.klooni.game.Cell; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.interfaces; /** * IEffectFactory interface has to be implemented for each effect. * <p> * It tells the name and the price of the effect and will create it, when needed. * * @see IEffect */ public interface IEffectFactory { String getName(); String getDisplay(); int getPrice();
IEffect create(final Cell deadCell, final Vector2 culprit);
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/game/GameLayout.java
// Path: core/src/dev/lonami/klooni/actors/Band.java // public class Band extends Actor { // // //region Members // // private final BaseScorer scorer; // private final Texture bandTexture; // // public final Rectangle scoreBounds; // public final Rectangle infoBounds; // // private final Label infoLabel; // private final Label scoreLabel; // // //endregion // // //region Constructor // // public Band(final Klooni game, final GameLayout layout, final BaseScorer scorer) { // this.scorer = scorer; // bandTexture = Theme.getBlankTexture(); // // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font"); // // scoreLabel = new Label("", labelStyle); // scoreLabel.setAlignment(Align.center); // infoLabel = new Label("pause menu", labelStyle); // infoLabel.setAlignment(Align.center); // // scoreBounds = new Rectangle(); // infoBounds = new Rectangle(); // layout.update(this); // } // // //endregion // // //region Public methods // // @Override // public void draw(Batch batch, float parentAlpha) { // // TODO This is not the best way to apply the transformation, but, oh well // float x = getParent().getX(); // float y = getParent().getY(); // // // TODO For some strange reason, the texture coordinates and label coordinates are different // Vector2 pos = localToStageCoordinates(new Vector2(x, y)); // batch.setColor(Klooni.theme.bandColor); // batch.draw(bandTexture, pos.x, pos.y, getWidth(), getHeight()); // // scoreLabel.setBounds(x + scoreBounds.x, y + scoreBounds.y, scoreBounds.width, scoreBounds.height); // scoreLabel.setText(Integer.toString(scorer.getCurrentScore())); // scoreLabel.setColor(Klooni.theme.textColor); // scoreLabel.draw(batch, parentAlpha); // // infoLabel.setBounds(x + infoBounds.x, y + infoBounds.y, infoBounds.width, infoBounds.height); // infoLabel.setColor(Klooni.theme.textColor); // infoLabel.draw(batch, parentAlpha); // } // // // Once game over is set on the menu, it cannot be reverted // public void setMessage(final String message) { // if (!message.equals("")) // infoLabel.setText(message); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/actors/ShopCard.java // public abstract class ShopCard extends Actor { // // final Klooni game; // // private final Label nameLabel; // final Label priceLabel; // // public final Rectangle nameBounds; // public final Rectangle priceBounds; // // public float cellSize; // // ShopCard(final Klooni game, final GameLayout layout, // final String itemName, final Color backgroundColor) { // this.game = game; // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font_small"); // // priceLabel = new Label("", labelStyle); // nameLabel = new Label(itemName, labelStyle); // // Color labelColor = Theme.shouldUseWhite(backgroundColor) ? Color.WHITE : Color.BLACK; // priceLabel.setColor(labelColor); // nameLabel.setColor(labelColor); // // priceBounds = new Rectangle(); // nameBounds = new Rectangle(); // // layout.update(this); // } // // @Override // public void draw(Batch batch, float parentAlpha) { // super.draw(batch, parentAlpha); // // final float x = getX(), y = getY(); // nameLabel.setBounds(x + nameBounds.x, y + nameBounds.y, nameBounds.width, nameBounds.height); // nameLabel.draw(batch, parentAlpha); // // priceLabel.setBounds(x + priceBounds.x, y + priceBounds.y, priceBounds.width, priceBounds.height); // priceLabel.draw(batch, parentAlpha); // } // // // Showcases the current effect (the shop will be showcasing them, one by one) // // This method should be called on the same card as long as it returns true. // // It should return false once it's done so that the next card can be showcased. // public boolean showcase(Batch batch, float yDisplacement) { // return false; // } // // public abstract void usedItemUpdated(); // // public abstract void use(); // // public abstract boolean isBought(); // // public abstract boolean isUsed(); // // public abstract float getPrice(); // // public abstract void performBuy(); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.ui.Label; import dev.lonami.klooni.actors.Band; import dev.lonami.klooni.actors.ShopCard;
area.x, area.y, area.width * 0.5f - cupSize * 0.5f, area.height); scorer.highScoreLabel.setBounds( area.x + area.width * 0.5f + cupSize * 0.5f, area.y, area.width * 0.5f - cupSize * 0.5f, area.height); } // Special case, we want to position the label on top of the cup void updateTimeLeftLabel(Label timeLeftLabel) { timeLeftLabel.setBounds(0, screenHeight - logoHeight, screenWidth, logoHeight); } void update(Board board) { // We can't leave our area, so pick the minimum between available // height and width to determine an appropriated cell size float boardSize = Math.min(availableWidth, boardHeight); board.cellSize = boardSize / board.cellCount; // Now that we know the board size, we can center the board on the screen board.pos.set( screenWidth * 0.5f - boardSize * 0.5f, pieceHolderHeight); } void update(PieceHolder holder) { holder.area.set( marginWidth, 0f, availableWidth, pieceHolderHeight); }
// Path: core/src/dev/lonami/klooni/actors/Band.java // public class Band extends Actor { // // //region Members // // private final BaseScorer scorer; // private final Texture bandTexture; // // public final Rectangle scoreBounds; // public final Rectangle infoBounds; // // private final Label infoLabel; // private final Label scoreLabel; // // //endregion // // //region Constructor // // public Band(final Klooni game, final GameLayout layout, final BaseScorer scorer) { // this.scorer = scorer; // bandTexture = Theme.getBlankTexture(); // // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font"); // // scoreLabel = new Label("", labelStyle); // scoreLabel.setAlignment(Align.center); // infoLabel = new Label("pause menu", labelStyle); // infoLabel.setAlignment(Align.center); // // scoreBounds = new Rectangle(); // infoBounds = new Rectangle(); // layout.update(this); // } // // //endregion // // //region Public methods // // @Override // public void draw(Batch batch, float parentAlpha) { // // TODO This is not the best way to apply the transformation, but, oh well // float x = getParent().getX(); // float y = getParent().getY(); // // // TODO For some strange reason, the texture coordinates and label coordinates are different // Vector2 pos = localToStageCoordinates(new Vector2(x, y)); // batch.setColor(Klooni.theme.bandColor); // batch.draw(bandTexture, pos.x, pos.y, getWidth(), getHeight()); // // scoreLabel.setBounds(x + scoreBounds.x, y + scoreBounds.y, scoreBounds.width, scoreBounds.height); // scoreLabel.setText(Integer.toString(scorer.getCurrentScore())); // scoreLabel.setColor(Klooni.theme.textColor); // scoreLabel.draw(batch, parentAlpha); // // infoLabel.setBounds(x + infoBounds.x, y + infoBounds.y, infoBounds.width, infoBounds.height); // infoLabel.setColor(Klooni.theme.textColor); // infoLabel.draw(batch, parentAlpha); // } // // // Once game over is set on the menu, it cannot be reverted // public void setMessage(final String message) { // if (!message.equals("")) // infoLabel.setText(message); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/actors/ShopCard.java // public abstract class ShopCard extends Actor { // // final Klooni game; // // private final Label nameLabel; // final Label priceLabel; // // public final Rectangle nameBounds; // public final Rectangle priceBounds; // // public float cellSize; // // ShopCard(final Klooni game, final GameLayout layout, // final String itemName, final Color backgroundColor) { // this.game = game; // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font_small"); // // priceLabel = new Label("", labelStyle); // nameLabel = new Label(itemName, labelStyle); // // Color labelColor = Theme.shouldUseWhite(backgroundColor) ? Color.WHITE : Color.BLACK; // priceLabel.setColor(labelColor); // nameLabel.setColor(labelColor); // // priceBounds = new Rectangle(); // nameBounds = new Rectangle(); // // layout.update(this); // } // // @Override // public void draw(Batch batch, float parentAlpha) { // super.draw(batch, parentAlpha); // // final float x = getX(), y = getY(); // nameLabel.setBounds(x + nameBounds.x, y + nameBounds.y, nameBounds.width, nameBounds.height); // nameLabel.draw(batch, parentAlpha); // // priceLabel.setBounds(x + priceBounds.x, y + priceBounds.y, priceBounds.width, priceBounds.height); // priceLabel.draw(batch, parentAlpha); // } // // // Showcases the current effect (the shop will be showcasing them, one by one) // // This method should be called on the same card as long as it returns true. // // It should return false once it's done so that the next card can be showcased. // public boolean showcase(Batch batch, float yDisplacement) { // return false; // } // // public abstract void usedItemUpdated(); // // public abstract void use(); // // public abstract boolean isBought(); // // public abstract boolean isUsed(); // // public abstract float getPrice(); // // public abstract void performBuy(); // } // Path: core/src/dev/lonami/klooni/game/GameLayout.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.ui.Label; import dev.lonami.klooni.actors.Band; import dev.lonami.klooni.actors.ShopCard; area.x, area.y, area.width * 0.5f - cupSize * 0.5f, area.height); scorer.highScoreLabel.setBounds( area.x + area.width * 0.5f + cupSize * 0.5f, area.y, area.width * 0.5f - cupSize * 0.5f, area.height); } // Special case, we want to position the label on top of the cup void updateTimeLeftLabel(Label timeLeftLabel) { timeLeftLabel.setBounds(0, screenHeight - logoHeight, screenWidth, logoHeight); } void update(Board board) { // We can't leave our area, so pick the minimum between available // height and width to determine an appropriated cell size float boardSize = Math.min(availableWidth, boardHeight); board.cellSize = boardSize / board.cellCount; // Now that we know the board size, we can center the board on the screen board.pos.set( screenWidth * 0.5f - boardSize * 0.5f, pieceHolderHeight); } void update(PieceHolder holder) { holder.area.set( marginWidth, 0f, availableWidth, pieceHolderHeight); }
public void update(Band band) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/game/GameLayout.java
// Path: core/src/dev/lonami/klooni/actors/Band.java // public class Band extends Actor { // // //region Members // // private final BaseScorer scorer; // private final Texture bandTexture; // // public final Rectangle scoreBounds; // public final Rectangle infoBounds; // // private final Label infoLabel; // private final Label scoreLabel; // // //endregion // // //region Constructor // // public Band(final Klooni game, final GameLayout layout, final BaseScorer scorer) { // this.scorer = scorer; // bandTexture = Theme.getBlankTexture(); // // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font"); // // scoreLabel = new Label("", labelStyle); // scoreLabel.setAlignment(Align.center); // infoLabel = new Label("pause menu", labelStyle); // infoLabel.setAlignment(Align.center); // // scoreBounds = new Rectangle(); // infoBounds = new Rectangle(); // layout.update(this); // } // // //endregion // // //region Public methods // // @Override // public void draw(Batch batch, float parentAlpha) { // // TODO This is not the best way to apply the transformation, but, oh well // float x = getParent().getX(); // float y = getParent().getY(); // // // TODO For some strange reason, the texture coordinates and label coordinates are different // Vector2 pos = localToStageCoordinates(new Vector2(x, y)); // batch.setColor(Klooni.theme.bandColor); // batch.draw(bandTexture, pos.x, pos.y, getWidth(), getHeight()); // // scoreLabel.setBounds(x + scoreBounds.x, y + scoreBounds.y, scoreBounds.width, scoreBounds.height); // scoreLabel.setText(Integer.toString(scorer.getCurrentScore())); // scoreLabel.setColor(Klooni.theme.textColor); // scoreLabel.draw(batch, parentAlpha); // // infoLabel.setBounds(x + infoBounds.x, y + infoBounds.y, infoBounds.width, infoBounds.height); // infoLabel.setColor(Klooni.theme.textColor); // infoLabel.draw(batch, parentAlpha); // } // // // Once game over is set on the menu, it cannot be reverted // public void setMessage(final String message) { // if (!message.equals("")) // infoLabel.setText(message); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/actors/ShopCard.java // public abstract class ShopCard extends Actor { // // final Klooni game; // // private final Label nameLabel; // final Label priceLabel; // // public final Rectangle nameBounds; // public final Rectangle priceBounds; // // public float cellSize; // // ShopCard(final Klooni game, final GameLayout layout, // final String itemName, final Color backgroundColor) { // this.game = game; // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font_small"); // // priceLabel = new Label("", labelStyle); // nameLabel = new Label(itemName, labelStyle); // // Color labelColor = Theme.shouldUseWhite(backgroundColor) ? Color.WHITE : Color.BLACK; // priceLabel.setColor(labelColor); // nameLabel.setColor(labelColor); // // priceBounds = new Rectangle(); // nameBounds = new Rectangle(); // // layout.update(this); // } // // @Override // public void draw(Batch batch, float parentAlpha) { // super.draw(batch, parentAlpha); // // final float x = getX(), y = getY(); // nameLabel.setBounds(x + nameBounds.x, y + nameBounds.y, nameBounds.width, nameBounds.height); // nameLabel.draw(batch, parentAlpha); // // priceLabel.setBounds(x + priceBounds.x, y + priceBounds.y, priceBounds.width, priceBounds.height); // priceLabel.draw(batch, parentAlpha); // } // // // Showcases the current effect (the shop will be showcasing them, one by one) // // This method should be called on the same card as long as it returns true. // // It should return false once it's done so that the next card can be showcased. // public boolean showcase(Batch batch, float yDisplacement) { // return false; // } // // public abstract void usedItemUpdated(); // // public abstract void use(); // // public abstract boolean isBought(); // // public abstract boolean isUsed(); // // public abstract float getPrice(); // // public abstract void performBuy(); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.ui.Label; import dev.lonami.klooni.actors.Band; import dev.lonami.klooni.actors.ShopCard;
board.cellSize = boardSize / board.cellCount; // Now that we know the board size, we can center the board on the screen board.pos.set( screenWidth * 0.5f - boardSize * 0.5f, pieceHolderHeight); } void update(PieceHolder holder) { holder.area.set( marginWidth, 0f, availableWidth, pieceHolderHeight); } public void update(Band band) { final Rectangle area = new Rectangle( 0, pieceHolderHeight + boardHeight, screenWidth, scoreHeight); band.setBounds(area.x, area.y, area.width, area.height); // Let the band have the following shape: // 10% (100) padding // 35% (90%) score label // 10% (55%) padding // 35% (45%) info label // 10% (10%) padding band.scoreBounds.set(area.x, area.y + area.height * 0.55f, area.width, area.height * 0.35f); band.infoBounds.set(area.x, area.y + area.height * 0.10f, area.width, area.height * 0.35f); } @SuppressWarnings("SuspiciousNameCombination")
// Path: core/src/dev/lonami/klooni/actors/Band.java // public class Band extends Actor { // // //region Members // // private final BaseScorer scorer; // private final Texture bandTexture; // // public final Rectangle scoreBounds; // public final Rectangle infoBounds; // // private final Label infoLabel; // private final Label scoreLabel; // // //endregion // // //region Constructor // // public Band(final Klooni game, final GameLayout layout, final BaseScorer scorer) { // this.scorer = scorer; // bandTexture = Theme.getBlankTexture(); // // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font"); // // scoreLabel = new Label("", labelStyle); // scoreLabel.setAlignment(Align.center); // infoLabel = new Label("pause menu", labelStyle); // infoLabel.setAlignment(Align.center); // // scoreBounds = new Rectangle(); // infoBounds = new Rectangle(); // layout.update(this); // } // // //endregion // // //region Public methods // // @Override // public void draw(Batch batch, float parentAlpha) { // // TODO This is not the best way to apply the transformation, but, oh well // float x = getParent().getX(); // float y = getParent().getY(); // // // TODO For some strange reason, the texture coordinates and label coordinates are different // Vector2 pos = localToStageCoordinates(new Vector2(x, y)); // batch.setColor(Klooni.theme.bandColor); // batch.draw(bandTexture, pos.x, pos.y, getWidth(), getHeight()); // // scoreLabel.setBounds(x + scoreBounds.x, y + scoreBounds.y, scoreBounds.width, scoreBounds.height); // scoreLabel.setText(Integer.toString(scorer.getCurrentScore())); // scoreLabel.setColor(Klooni.theme.textColor); // scoreLabel.draw(batch, parentAlpha); // // infoLabel.setBounds(x + infoBounds.x, y + infoBounds.y, infoBounds.width, infoBounds.height); // infoLabel.setColor(Klooni.theme.textColor); // infoLabel.draw(batch, parentAlpha); // } // // // Once game over is set on the menu, it cannot be reverted // public void setMessage(final String message) { // if (!message.equals("")) // infoLabel.setText(message); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/actors/ShopCard.java // public abstract class ShopCard extends Actor { // // final Klooni game; // // private final Label nameLabel; // final Label priceLabel; // // public final Rectangle nameBounds; // public final Rectangle priceBounds; // // public float cellSize; // // ShopCard(final Klooni game, final GameLayout layout, // final String itemName, final Color backgroundColor) { // this.game = game; // Label.LabelStyle labelStyle = new Label.LabelStyle(); // labelStyle.font = game.skin.getFont("font_small"); // // priceLabel = new Label("", labelStyle); // nameLabel = new Label(itemName, labelStyle); // // Color labelColor = Theme.shouldUseWhite(backgroundColor) ? Color.WHITE : Color.BLACK; // priceLabel.setColor(labelColor); // nameLabel.setColor(labelColor); // // priceBounds = new Rectangle(); // nameBounds = new Rectangle(); // // layout.update(this); // } // // @Override // public void draw(Batch batch, float parentAlpha) { // super.draw(batch, parentAlpha); // // final float x = getX(), y = getY(); // nameLabel.setBounds(x + nameBounds.x, y + nameBounds.y, nameBounds.width, nameBounds.height); // nameLabel.draw(batch, parentAlpha); // // priceLabel.setBounds(x + priceBounds.x, y + priceBounds.y, priceBounds.width, priceBounds.height); // priceLabel.draw(batch, parentAlpha); // } // // // Showcases the current effect (the shop will be showcasing them, one by one) // // This method should be called on the same card as long as it returns true. // // It should return false once it's done so that the next card can be showcased. // public boolean showcase(Batch batch, float yDisplacement) { // return false; // } // // public abstract void usedItemUpdated(); // // public abstract void use(); // // public abstract boolean isBought(); // // public abstract boolean isUsed(); // // public abstract float getPrice(); // // public abstract void performBuy(); // } // Path: core/src/dev/lonami/klooni/game/GameLayout.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.ui.Label; import dev.lonami.klooni.actors.Band; import dev.lonami.klooni.actors.ShopCard; board.cellSize = boardSize / board.cellCount; // Now that we know the board size, we can center the board on the screen board.pos.set( screenWidth * 0.5f - boardSize * 0.5f, pieceHolderHeight); } void update(PieceHolder holder) { holder.area.set( marginWidth, 0f, availableWidth, pieceHolderHeight); } public void update(Band band) { final Rectangle area = new Rectangle( 0, pieceHolderHeight + boardHeight, screenWidth, scoreHeight); band.setBounds(area.x, area.y, area.width, area.height); // Let the band have the following shape: // 10% (100) padding // 35% (90%) score label // 10% (55%) padding // 35% (45%) info label // 10% (10%) padding band.scoreBounds.set(area.x, area.y + area.height * 0.55f, area.width, area.height * 0.35f); band.infoBounds.set(area.x, area.y + area.height * 0.10f, area.width, area.height * 0.35f); } @SuppressWarnings("SuspiciousNameCombination")
public void update(ShopCard card) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/ExplodeEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class ExplodeEffectFactory implements IEffectFactory { @Override public String getName() { return "explode"; } @Override public String getDisplay() { return "Explode"; } @Override public int getPrice() { return 200; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/ExplodeEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class ExplodeEffectFactory implements IEffectFactory { @Override public String getName() { return "explode"; } @Override public String getDisplay() { return "Explode"; } @Override public int getPrice() { return 200; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
LonamiWebs/Klooni1010
core/src/dev/lonami/klooni/effects/ExplodeEffectFactory.java
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory;
/* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class ExplodeEffectFactory implements IEffectFactory { @Override public String getName() { return "explode"; } @Override public String getDisplay() { return "Explode"; } @Override public int getPrice() { return 200; } @Override
// Path: core/src/dev/lonami/klooni/game/Cell.java // public class Cell implements BinSerializable { // // //region Members // // // Negative index indicates that the cell is empty // private int colorIndex; // // public final Vector2 pos; // public final float size; // // //endregion // // //region Constructor // // Cell(float x, float y, float cellSize) { // pos = new Vector2(x, y); // size = cellSize; // // colorIndex = -1; // } // // //endregion // // //region Package local methods // // // Sets the cell to be non-empty and of the specified color index // public void set(int ci) { // colorIndex = ci; // } // // public void draw(Batch batch) { // // Always query the color to the theme, because it might have changed // draw(Klooni.theme.getCellColor(colorIndex), batch, pos.x, pos.y, size); // } // // public Color getColorCopy() { // return Klooni.theme.getCellColor(colorIndex).cpy(); // } // // boolean isEmpty() { // return colorIndex < 0; // } // // //endregion // // //region Static methods // // // Default texture (don't call overloaded version to avoid overhead) // public static void draw(final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(Klooni.theme.cellTexture, x, y, size, size); // } // // // Custom texture // public static void draw(final Texture texture, final Color color, final Batch batch, // final float x, final float y, final float size) { // batch.setColor(color); // batch.draw(texture, x, y, size, size); // } // // //endregion // // //region Serialization // // @Override // public void write(DataOutputStream out) throws IOException { // // Only the color index is saved // out.writeInt(colorIndex); // } // // @Override // public void read(DataInputStream in) throws IOException { // colorIndex = in.readInt(); // } // // //endregion // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffect.java // public interface IEffect { // void setInfo(Cell deadCell, Vector2 culprit); // // void draw(Batch batch); // // boolean isDone(); // } // // Path: core/src/dev/lonami/klooni/interfaces/IEffectFactory.java // public interface IEffectFactory { // String getName(); // // String getDisplay(); // // int getPrice(); // // IEffect create(final Cell deadCell, final Vector2 culprit); // } // Path: core/src/dev/lonami/klooni/effects/ExplodeEffectFactory.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import dev.lonami.klooni.game.Cell; import dev.lonami.klooni.interfaces.IEffect; import dev.lonami.klooni.interfaces.IEffectFactory; /* 1010! Klooni, a free customizable puzzle game for Android and Desktop Copyright (C) 2017-2019 Lonami Exo @ lonami.dev This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dev.lonami.klooni.effects; public class ExplodeEffectFactory implements IEffectFactory { @Override public String getName() { return "explode"; } @Override public String getDisplay() { return "Explode"; } @Override public int getPrice() { return 200; } @Override
public IEffect create(Cell deadCell, Vector2 culprit) {
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/Utils.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import java.io.IOException; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.slf4j.Logger; import org.trend.hgraph.HBaseGraphConstants;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.mapreduce.pagerank; /** * A Utility class * @author scott_miao */ class Utils { static void writePageRank(HTable table, String rowkey, String columnQualifer, double pageRank) { Put put = null; put = new Put(Bytes.toBytes(rowkey)); put.add(
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/Utils.java import java.io.IOException; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.slf4j.Logger; import org.trend.hgraph.HBaseGraphConstants; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.mapreduce.pagerank; /** * A Utility class * @author scott_miao */ class Utils { static void writePageRank(HTable table, String rowkey, String columnQualifer, double pageRank) { Put put = null; put = new Put(Bytes.toBytes(rowkey)); put.add(
Bytes.toBytes(HBaseGraphConstants.HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME),
trendmicro/HGraph
src/test/java/org/trend/hgraph/mapreduce/pagerank/LocalPrTest.java
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculatePageRankReducer.java // static boolean pageRankEquals(double src, double dest, int scale) { // BigDecimal a = new BigDecimal(src); // BigDecimal b = new BigDecimal(dest); // a = a.setScale(scale, RoundingMode.DOWN); // b = b.setScale(scale, RoundingMode.DOWN); // return a.compareTo(b) == 0 ? true : false; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.trend.hgraph.HBaseGraphConstants; import static org.trend.hgraph.mapreduce.pagerank.CalculatePageRankReducer.pageRankEquals; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.junit.After; import org.junit.AfterClass;
int prChanged = 0; int round = 0; do { round++; prChanged = 0; // housekeeping for (V v : vs) v.tprs.clear(); // as mapper double cpr = 0.0D; double tpr = 0.0D; for (V v : vs) { cpr = v.pr; tpr = cpr / (double) v.al.size(); for (V alv : v.al) alv.tprs.add(tpr); } // as reducer double opr = 0.0D; double pr = 0.0D; double npr = 0.0D; for (V v : vs) { opr = v.pr; pr = 0.0D; for (double tpr1 : v.tprs) { pr = pr + tpr1; } npr = (0.85D * pr) + ((1.0D - 0.85D) / (double) vs.size());
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculatePageRankReducer.java // static boolean pageRankEquals(double src, double dest, int scale) { // BigDecimal a = new BigDecimal(src); // BigDecimal b = new BigDecimal(dest); // a = a.setScale(scale, RoundingMode.DOWN); // b = b.setScale(scale, RoundingMode.DOWN); // return a.compareTo(b) == 0 ? true : false; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/test/java/org/trend/hgraph/mapreduce/pagerank/LocalPrTest.java import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.trend.hgraph.HBaseGraphConstants; import static org.trend.hgraph.mapreduce.pagerank.CalculatePageRankReducer.pageRankEquals; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.junit.After; import org.junit.AfterClass; int prChanged = 0; int round = 0; do { round++; prChanged = 0; // housekeeping for (V v : vs) v.tprs.clear(); // as mapper double cpr = 0.0D; double tpr = 0.0D; for (V v : vs) { cpr = v.pr; tpr = cpr / (double) v.al.size(); for (V alv : v.al) alv.tprs.add(tpr); } // as reducer double opr = 0.0D; double pr = 0.0D; double npr = 0.0D; for (V v : vs) { opr = v.pr; pr = 0.0D; for (double tpr1 : v.tprs) { pr = pr + tpr1; } npr = (0.85D * pr) + ((1.0D - 0.85D) / (double) vs.size());
if (!pageRankEquals(opr, npr, 3)) prChanged++;
trendmicro/HGraph
src/test/java/org/trend/hgraph/mapreduce/pagerank/LocalPrTest.java
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculatePageRankReducer.java // static boolean pageRankEquals(double src, double dest, int scale) { // BigDecimal a = new BigDecimal(src); // BigDecimal b = new BigDecimal(dest); // a = a.setScale(scale, RoundingMode.DOWN); // b = b.setScale(scale, RoundingMode.DOWN); // return a.compareTo(b) == 0 ? true : false; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.trend.hgraph.HBaseGraphConstants; import static org.trend.hgraph.mapreduce.pagerank.CalculatePageRankReducer.pageRankEquals; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.junit.After; import org.junit.AfterClass;
DriverTest.class.getClassLoader().getResourceAsStream(vertexData); LineIterator it = IOUtils.lineIterator(new InputStreamReader(data)); // load all Vs List<V> vs = new ArrayList<V>(); String record = null; String[] values = null; V v = null; while (it.hasNext()) { record = it.next(); values = record.split("\\|"); Assert.assertNotNull(values); Assert.assertEquals(2, values.length); v = new V(); v.key = values[0]; v.pr = Double.parseDouble(values[1]); vs.add(v); } LineIterator.closeQuietly(it); IOUtils.closeQuietly(data); // build adjacency list data = DriverTest.class.getClassLoader().getResourceAsStream(edgeData); it = IOUtils.lineIterator(new InputStreamReader(data)); while (it.hasNext()) { record = it.next(); values = record.split("\\|"); Assert.assertNotNull(values); Assert.assertEquals(2, values.length);
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculatePageRankReducer.java // static boolean pageRankEquals(double src, double dest, int scale) { // BigDecimal a = new BigDecimal(src); // BigDecimal b = new BigDecimal(dest); // a = a.setScale(scale, RoundingMode.DOWN); // b = b.setScale(scale, RoundingMode.DOWN); // return a.compareTo(b) == 0 ? true : false; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/test/java/org/trend/hgraph/mapreduce/pagerank/LocalPrTest.java import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.trend.hgraph.HBaseGraphConstants; import static org.trend.hgraph.mapreduce.pagerank.CalculatePageRankReducer.pageRankEquals; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.junit.After; import org.junit.AfterClass; DriverTest.class.getClassLoader().getResourceAsStream(vertexData); LineIterator it = IOUtils.lineIterator(new InputStreamReader(data)); // load all Vs List<V> vs = new ArrayList<V>(); String record = null; String[] values = null; V v = null; while (it.hasNext()) { record = it.next(); values = record.split("\\|"); Assert.assertNotNull(values); Assert.assertEquals(2, values.length); v = new V(); v.key = values[0]; v.pr = Double.parseDouble(values[1]); vs.add(v); } LineIterator.closeQuietly(it); IOUtils.closeQuietly(data); // build adjacency list data = DriverTest.class.getClassLoader().getResourceAsStream(edgeData); it = IOUtils.lineIterator(new InputStreamReader(data)); while (it.hasNext()) { record = it.next(); values = record.split("\\|"); Assert.assertNotNull(values); Assert.assertEquals(2, values.length);
values = values[0].split(HBaseGraphConstants.HBASE_GRAPH_TABLE_EDGE_DELIMITER_1);
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculatePageRankReducer.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import org.apache.commons.lang.time.StopWatch; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.trend.hgraph.HBaseGraphConstants;
sw.reset(); sw.start(); double oldPageRank = Utils.getPageRank(vertexTable, rowkey, Constants.PAGE_RANK_CQ_TMP_NAME); if (!pageRankEquals(oldPageRank, newPageRank, pageRankCompareScale)) { // collect pageRank changing count with counter context.getCounter(Counters.CHANGED_PAGE_RANK_COUNT).increment(1); } sw.stop(); context.getCounter(Counters.CMP_OLD_NEW_PR_TIME_CONSUMED).increment(sw.getTime()); context.write(key, new DoubleWritable(newPageRank)); } static boolean pageRankEquals(double src, double dest, int scale) { BigDecimal a = new BigDecimal(src); BigDecimal b = new BigDecimal(dest); a = a.setScale(scale, RoundingMode.DOWN); b = b.setScale(scale, RoundingMode.DOWN); return a.compareTo(b) == 0 ? true : false; } /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Reducer#setup(org.apache.hadoop.mapreduce.Reducer.Context) */ @Override protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); vertexTable =
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculatePageRankReducer.java import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import org.apache.commons.lang.time.StopWatch; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.trend.hgraph.HBaseGraphConstants; sw.reset(); sw.start(); double oldPageRank = Utils.getPageRank(vertexTable, rowkey, Constants.PAGE_RANK_CQ_TMP_NAME); if (!pageRankEquals(oldPageRank, newPageRank, pageRankCompareScale)) { // collect pageRank changing count with counter context.getCounter(Counters.CHANGED_PAGE_RANK_COUNT).increment(1); } sw.stop(); context.getCounter(Counters.CMP_OLD_NEW_PR_TIME_CONSUMED).increment(sw.getTime()); context.write(key, new DoubleWritable(newPageRank)); } static boolean pageRankEquals(double src, double dest, int scale) { BigDecimal a = new BigDecimal(src); BigDecimal b = new BigDecimal(dest); a = a.setScale(scale, RoundingMode.DOWN); b = b.setScale(scale, RoundingMode.DOWN); return a.compareTo(b) == 0 ? true : false; } /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Reducer#setup(org.apache.hadoop.mapreduce.Reducer.Context) */ @Override protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); vertexTable =
Utils.initTable(conf, HBaseGraphConstants.HBASE_GRAPH_TABLE_VERTEX_NAME_KEY,
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/lib/input/CalculateInputSplitMapper.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableInputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants;
} } private static String getKeyString(byte[] bkey) { String key = null; key = Bytes.toString(bkey).trim(); key = key + EMPTY_STRING; return key; } @Override protected void cleanup(Context context) throws IOException, InterruptedException { vertexTable.close(); } @Override protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); bypassKeys = conf.getInt(BY_PASS_KEYS, bypassKeys); String vertexTableName = conf.get(TableInputFormat.INPUT_TABLE); if (null == vertexTableName || "".equals(vertexTableName)) { throw new IllegalArgumentException(TableInputFormat.INPUT_TABLE + " shall not be empty or null"); } vertexTable = new HTable(conf, vertexTableName); } } private static Job createInputSplitMapperJob(Configuration conf, String outputPath) throws IOException {
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/lib/input/CalculateInputSplitMapper.java import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableInputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants; } } private static String getKeyString(byte[] bkey) { String key = null; key = Bytes.toString(bkey).trim(); key = key + EMPTY_STRING; return key; } @Override protected void cleanup(Context context) throws IOException, InterruptedException { vertexTable.close(); } @Override protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); bypassKeys = conf.getInt(BY_PASS_KEYS, bypassKeys); String vertexTableName = conf.get(TableInputFormat.INPUT_TABLE); if (null == vertexTableName || "".equals(vertexTableName)) { throw new IllegalArgumentException(TableInputFormat.INPUT_TABLE + " shall not be empty or null"); } vertexTable = new HTable(conf, vertexTableName); } } private static Job createInputSplitMapperJob(Configuration conf, String outputPath) throws IOException {
String tableName = conf.get(HBaseGraphConstants.HBASE_GRAPH_TABLE_VERTEX_NAME_KEY);
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.trend.hgraph.HBaseGraphConstants; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang.time.StopWatch; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapper;
InterruptedException { int outgoingEdgeCount = outgoingRowKeys.size(); outgoingEdgeCounter.increment(outgoingEdgeCount); double pageRankForEachOutgoing = pageRank / (double) outgoingEdgeCount; StopWatch sw = null; String outgoingRowKey = null; try { sw = new StopWatch(); sw.start(); for (int a = 0; a < outgoingRowKeys.size(); a++) { outgoingRowKey = outgoingRowKeys.get(a); strategy.write(outgoingRowKey, pageRankForEachOutgoing); } sw.stop(); dispatchPrTimeConsumeCounter.increment(sw.getTime()); } catch (IOException e) { System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); e.printStackTrace(System.err); throw e; } catch (InterruptedException e) { System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); e.printStackTrace(System.err); throw e; } } private static Scan getRowKeyOnlyScan(String rowKey) { Scan scan = new Scan(); scan.setStartRow(Bytes.toBytes(rowKey
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.trend.hgraph.HBaseGraphConstants; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang.time.StopWatch; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapper; InterruptedException { int outgoingEdgeCount = outgoingRowKeys.size(); outgoingEdgeCounter.increment(outgoingEdgeCount); double pageRankForEachOutgoing = pageRank / (double) outgoingEdgeCount; StopWatch sw = null; String outgoingRowKey = null; try { sw = new StopWatch(); sw.start(); for (int a = 0; a < outgoingRowKeys.size(); a++) { outgoingRowKey = outgoingRowKeys.get(a); strategy.write(outgoingRowKey, pageRankForEachOutgoing); } sw.stop(); dispatchPrTimeConsumeCounter.increment(sw.getTime()); } catch (IOException e) { System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); e.printStackTrace(System.err); throw e; } catch (InterruptedException e) { System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); e.printStackTrace(System.err); throw e; } } private static Scan getRowKeyOnlyScan(String rowKey) { Scan scan = new Scan(); scan.setStartRow(Bytes.toBytes(rowKey
+ HBaseGraphConstants.HBASE_GRAPH_TABLE_EDGE_DELIMITER_1));
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/ResetPageRankUpdateFlag.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.trend.hgraph.HBaseGraphConstants;
/** * */ package org.trend.hgraph.mapreduce.pagerank; /** * A MR to set {@link Constants#PAGE_RANK_CQ_UPDATED_NAME} flag to 0 * @author scott_miao */ public class ResetPageRankUpdateFlag extends Configured implements Tool { protected ResetPageRankUpdateFlag(Configuration conf) { super(conf); } private static class Mapper extends TableMapper<ImmutableBytesWritable, Put> { enum Counters { RESET_ROW_COUNT } @Override protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException { byte[] rowkey = key.get(); Put put = null; put = new Put(rowkey);
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/ResetPageRankUpdateFlag.java import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.trend.hgraph.HBaseGraphConstants; /** * */ package org.trend.hgraph.mapreduce.pagerank; /** * A MR to set {@link Constants#PAGE_RANK_CQ_UPDATED_NAME} flag to 0 * @author scott_miao */ public class ResetPageRankUpdateFlag extends Configured implements Tool { protected ResetPageRankUpdateFlag(Configuration conf) { super(conf); } private static class Mapper extends TableMapper<ImmutableBytesWritable, Put> { enum Counters { RESET_ROW_COUNT } @Override protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException { byte[] rowkey = key.get(); Put put = null; put = new Put(rowkey);
put.add(Bytes.toBytes(HBaseGraphConstants.HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME),
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateIntermediatePageRankMapper.java
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static void dispatchPageRank(List<String> outgoingRowKeys, double pageRank, Configuration conf, // HTable edgeTable, Counter dispatchPrTimeConsumeCounter, Counter outgoingEdgeCounter, // ContextWriterStrategy strategy) // throws IOException, // InterruptedException { // int outgoingEdgeCount = outgoingRowKeys.size(); // outgoingEdgeCounter.increment(outgoingEdgeCount); // double pageRankForEachOutgoing = pageRank / (double) outgoingEdgeCount; // // StopWatch sw = null; // String outgoingRowKey = null; // try { // sw = new StopWatch(); // sw.start(); // for (int a = 0; a < outgoingRowKeys.size(); a++) { // outgoingRowKey = outgoingRowKeys.get(a); // strategy.write(outgoingRowKey, pageRankForEachOutgoing); // } // sw.stop(); // dispatchPrTimeConsumeCounter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } catch (InterruptedException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static List<String> getOutgoingRowKeys(Configuration conf, HTable vertexTable, HTable edgeTable, // String rowKey, Counter counter) throws IOException { // ResultScanner rs = null; // String key = null; // LinkedList<String> rowKeys = new LinkedList<String>(); // StopWatch sw = null; // // Put put = null; // try { // Scan scan = getRowKeyOnlyScan(rowKey); // sw = new StopWatch(); // sw.start(); // rs = edgeTable.getScanner(scan); // for (Result r : rs) { // key = getOutgoingRowKey(r); // // collect outgoing rowkeys // rowKeys.add(key); // } // sw.stop(); // counter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("access htable:" + Bytes.toString(edgeTable.getTableName()) + " failed"); // e.printStackTrace(System.err); // throw e; // } finally { // rs.close(); // } // return rowKeys; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // interface ContextWriterStrategy { // void write(String key, double value) throws IOException, InterruptedException; // }
import org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.ContextWriterStrategy; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.dispatchPageRank; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.getOutgoingRowKeys; import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.trend.hgraph.HBaseGraphConstants;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.mapreduce.pagerank; /** * A <code>Mapper</code> for calculating intermediate pagerank value from HDFS. * @author scott_miao */ public class CalculateIntermediatePageRankMapper extends Mapper<Text, DoubleWritable, Text, DoubleWritable> { private HTable edgeTable = null; private HTable vertexTable = null; private String tmpPageRankCq = Constants.PAGE_RANK_CQ_TMP_NAME; enum Counters { VERTEX_COUNT, OUTGOING_EDGE_COUNT, GET_OUTGOING_VERTICES_TIME_CONSUMED, DISPATCH_PR_TIME_CONSUMED } /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#map(java.lang.Object, java.lang.Object, Context) */ @Override protected void map(final Text key, final DoubleWritable value, final Context context) throws IOException, InterruptedException { String rowKey = Bytes.toString(key.getBytes()).trim(); double pageRank = value.get(); // write current pageRank to tmp Utils.writePageRank(vertexTable, rowKey, tmpPageRankCq, pageRank); Configuration conf = context.getConfiguration(); List<String> outgoingRowKeys = null; context.getCounter(Counters.VERTEX_COUNT).increment(1); outgoingRowKeys =
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static void dispatchPageRank(List<String> outgoingRowKeys, double pageRank, Configuration conf, // HTable edgeTable, Counter dispatchPrTimeConsumeCounter, Counter outgoingEdgeCounter, // ContextWriterStrategy strategy) // throws IOException, // InterruptedException { // int outgoingEdgeCount = outgoingRowKeys.size(); // outgoingEdgeCounter.increment(outgoingEdgeCount); // double pageRankForEachOutgoing = pageRank / (double) outgoingEdgeCount; // // StopWatch sw = null; // String outgoingRowKey = null; // try { // sw = new StopWatch(); // sw.start(); // for (int a = 0; a < outgoingRowKeys.size(); a++) { // outgoingRowKey = outgoingRowKeys.get(a); // strategy.write(outgoingRowKey, pageRankForEachOutgoing); // } // sw.stop(); // dispatchPrTimeConsumeCounter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } catch (InterruptedException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static List<String> getOutgoingRowKeys(Configuration conf, HTable vertexTable, HTable edgeTable, // String rowKey, Counter counter) throws IOException { // ResultScanner rs = null; // String key = null; // LinkedList<String> rowKeys = new LinkedList<String>(); // StopWatch sw = null; // // Put put = null; // try { // Scan scan = getRowKeyOnlyScan(rowKey); // sw = new StopWatch(); // sw.start(); // rs = edgeTable.getScanner(scan); // for (Result r : rs) { // key = getOutgoingRowKey(r); // // collect outgoing rowkeys // rowKeys.add(key); // } // sw.stop(); // counter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("access htable:" + Bytes.toString(edgeTable.getTableName()) + " failed"); // e.printStackTrace(System.err); // throw e; // } finally { // rs.close(); // } // return rowKeys; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // interface ContextWriterStrategy { // void write(String key, double value) throws IOException, InterruptedException; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateIntermediatePageRankMapper.java import org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.ContextWriterStrategy; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.dispatchPageRank; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.getOutgoingRowKeys; import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.trend.hgraph.HBaseGraphConstants; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.mapreduce.pagerank; /** * A <code>Mapper</code> for calculating intermediate pagerank value from HDFS. * @author scott_miao */ public class CalculateIntermediatePageRankMapper extends Mapper<Text, DoubleWritable, Text, DoubleWritable> { private HTable edgeTable = null; private HTable vertexTable = null; private String tmpPageRankCq = Constants.PAGE_RANK_CQ_TMP_NAME; enum Counters { VERTEX_COUNT, OUTGOING_EDGE_COUNT, GET_OUTGOING_VERTICES_TIME_CONSUMED, DISPATCH_PR_TIME_CONSUMED } /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#map(java.lang.Object, java.lang.Object, Context) */ @Override protected void map(final Text key, final DoubleWritable value, final Context context) throws IOException, InterruptedException { String rowKey = Bytes.toString(key.getBytes()).trim(); double pageRank = value.get(); // write current pageRank to tmp Utils.writePageRank(vertexTable, rowKey, tmpPageRankCq, pageRank); Configuration conf = context.getConfiguration(); List<String> outgoingRowKeys = null; context.getCounter(Counters.VERTEX_COUNT).increment(1); outgoingRowKeys =
getOutgoingRowKeys(conf, vertexTable, edgeTable, rowKey,
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateIntermediatePageRankMapper.java
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static void dispatchPageRank(List<String> outgoingRowKeys, double pageRank, Configuration conf, // HTable edgeTable, Counter dispatchPrTimeConsumeCounter, Counter outgoingEdgeCounter, // ContextWriterStrategy strategy) // throws IOException, // InterruptedException { // int outgoingEdgeCount = outgoingRowKeys.size(); // outgoingEdgeCounter.increment(outgoingEdgeCount); // double pageRankForEachOutgoing = pageRank / (double) outgoingEdgeCount; // // StopWatch sw = null; // String outgoingRowKey = null; // try { // sw = new StopWatch(); // sw.start(); // for (int a = 0; a < outgoingRowKeys.size(); a++) { // outgoingRowKey = outgoingRowKeys.get(a); // strategy.write(outgoingRowKey, pageRankForEachOutgoing); // } // sw.stop(); // dispatchPrTimeConsumeCounter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } catch (InterruptedException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static List<String> getOutgoingRowKeys(Configuration conf, HTable vertexTable, HTable edgeTable, // String rowKey, Counter counter) throws IOException { // ResultScanner rs = null; // String key = null; // LinkedList<String> rowKeys = new LinkedList<String>(); // StopWatch sw = null; // // Put put = null; // try { // Scan scan = getRowKeyOnlyScan(rowKey); // sw = new StopWatch(); // sw.start(); // rs = edgeTable.getScanner(scan); // for (Result r : rs) { // key = getOutgoingRowKey(r); // // collect outgoing rowkeys // rowKeys.add(key); // } // sw.stop(); // counter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("access htable:" + Bytes.toString(edgeTable.getTableName()) + " failed"); // e.printStackTrace(System.err); // throw e; // } finally { // rs.close(); // } // return rowKeys; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // interface ContextWriterStrategy { // void write(String key, double value) throws IOException, InterruptedException; // }
import org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.ContextWriterStrategy; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.dispatchPageRank; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.getOutgoingRowKeys; import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.trend.hgraph.HBaseGraphConstants;
double pageRank = value.get(); // write current pageRank to tmp Utils.writePageRank(vertexTable, rowKey, tmpPageRankCq, pageRank); Configuration conf = context.getConfiguration(); List<String> outgoingRowKeys = null; context.getCounter(Counters.VERTEX_COUNT).increment(1); outgoingRowKeys = getOutgoingRowKeys(conf, vertexTable, edgeTable, rowKey, context.getCounter(Counters.GET_OUTGOING_VERTICES_TIME_CONSUMED)); dispatchPageRank(outgoingRowKeys, pageRank, conf, edgeTable, context.getCounter(Counters.DISPATCH_PR_TIME_CONSUMED), context.getCounter(Counters.OUTGOING_EDGE_COUNT), new ContextWriterStrategy() { @Override public void write(String key, double value) throws IOException, InterruptedException { context.write(new Text(key), new DoubleWritable(value)); } }); } /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#setup(Context) */ @Override protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); vertexTable =
// Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static void dispatchPageRank(List<String> outgoingRowKeys, double pageRank, Configuration conf, // HTable edgeTable, Counter dispatchPrTimeConsumeCounter, Counter outgoingEdgeCounter, // ContextWriterStrategy strategy) // throws IOException, // InterruptedException { // int outgoingEdgeCount = outgoingRowKeys.size(); // outgoingEdgeCounter.increment(outgoingEdgeCount); // double pageRankForEachOutgoing = pageRank / (double) outgoingEdgeCount; // // StopWatch sw = null; // String outgoingRowKey = null; // try { // sw = new StopWatch(); // sw.start(); // for (int a = 0; a < outgoingRowKeys.size(); a++) { // outgoingRowKey = outgoingRowKeys.get(a); // strategy.write(outgoingRowKey, pageRankForEachOutgoing); // } // sw.stop(); // dispatchPrTimeConsumeCounter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } catch (InterruptedException e) { // System.err.println("failed while writing outgoingRowKey:" + outgoingRowKey); // e.printStackTrace(System.err); // throw e; // } // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // static List<String> getOutgoingRowKeys(Configuration conf, HTable vertexTable, HTable edgeTable, // String rowKey, Counter counter) throws IOException { // ResultScanner rs = null; // String key = null; // LinkedList<String> rowKeys = new LinkedList<String>(); // StopWatch sw = null; // // Put put = null; // try { // Scan scan = getRowKeyOnlyScan(rowKey); // sw = new StopWatch(); // sw.start(); // rs = edgeTable.getScanner(scan); // for (Result r : rs) { // key = getOutgoingRowKey(r); // // collect outgoing rowkeys // rowKeys.add(key); // } // sw.stop(); // counter.increment(sw.getTime()); // } catch (IOException e) { // System.err.println("access htable:" + Bytes.toString(edgeTable.getTableName()) + " failed"); // e.printStackTrace(System.err); // throw e; // } finally { // rs.close(); // } // return rowKeys; // } // // Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateInitPageRankMapper.java // interface ContextWriterStrategy { // void write(String key, double value) throws IOException, InterruptedException; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/CalculateIntermediatePageRankMapper.java import org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.ContextWriterStrategy; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.dispatchPageRank; import static org.trend.hgraph.mapreduce.pagerank.CalculateInitPageRankMapper.getOutgoingRowKeys; import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.trend.hgraph.HBaseGraphConstants; double pageRank = value.get(); // write current pageRank to tmp Utils.writePageRank(vertexTable, rowKey, tmpPageRankCq, pageRank); Configuration conf = context.getConfiguration(); List<String> outgoingRowKeys = null; context.getCounter(Counters.VERTEX_COUNT).increment(1); outgoingRowKeys = getOutgoingRowKeys(conf, vertexTable, edgeTable, rowKey, context.getCounter(Counters.GET_OUTGOING_VERTICES_TIME_CONSUMED)); dispatchPageRank(outgoingRowKeys, pageRank, conf, edgeTable, context.getCounter(Counters.DISPATCH_PR_TIME_CONSUMED), context.getCounter(Counters.OUTGOING_EDGE_COUNT), new ContextWriterStrategy() { @Override public void write(String key, double value) throws IOException, InterruptedException { context.write(new Text(key), new DoubleWritable(value)); } }); } /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#setup(Context) */ @Override protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); vertexTable =
Utils.initTable(conf, HBaseGraphConstants.HBASE_GRAPH_TABLE_VERTEX_NAME_KEY,
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/Driver.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import java.io.IOException; import java.util.Arrays; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.mapreduce.RowCounter; import org.apache.hadoop.hbase.mapreduce.TableInputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants;
} } else if ("-p".equals(arg) || "--input-splits-path".equals(arg)) { a++; inputSplitsPath = args[a]; } else { System.err.println("Not a defined option:" + arg); printUsage(); return 1; } } else { // must if (startMustIdx < 0) startMustIdx = a; } } if (startMustIdx + 3 != args.length) { System.err.println("The must options not satisfied !!"); printUsage(); return 1; } LOGGER.info("start to run " + this.getClass().getName() + " with options:" + Arrays.toString(args)); Configuration conf = getConf(); Class<? extends TableInputFormat> tableInputFormat = TableInputFormat.class; String vertexTableName = args[startMustIdx]; String edgeTableName = args[startMustIdx + 1]; String outputBasePath = args[startMustIdx + 2];
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/Driver.java import java.io.IOException; import java.util.Arrays; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.mapreduce.RowCounter; import org.apache.hadoop.hbase.mapreduce.TableInputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants; } } else if ("-p".equals(arg) || "--input-splits-path".equals(arg)) { a++; inputSplitsPath = args[a]; } else { System.err.println("Not a defined option:" + arg); printUsage(); return 1; } } else { // must if (startMustIdx < 0) startMustIdx = a; } } if (startMustIdx + 3 != args.length) { System.err.println("The must options not satisfied !!"); printUsage(); return 1; } LOGGER.info("start to run " + this.getClass().getName() + " with options:" + Arrays.toString(args)); Configuration conf = getConf(); Class<? extends TableInputFormat> tableInputFormat = TableInputFormat.class; String vertexTableName = args[startMustIdx]; String edgeTableName = args[startMustIdx + 1]; String outputBasePath = args[startMustIdx + 2];
LOGGER.info(HBaseGraphConstants.HBASE_GRAPH_TABLE_VERTEX_NAME_KEY + "=" + vertexTableName);
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/pagerank/ImportPageRanks.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import java.io.IOException; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.mapreduce.pagerank; /** * Import pageRanks from <code>SeuquenceFile</code> into HBase. * By key => rowKey, value => pageRank. * @author scott_miao */ public class ImportPageRanks extends Configured implements Tool { private static Logger LOGGER = LoggerFactory.getLogger(ImportPageRanks.class); private static class ImportPageRanksMapper extends Mapper<Text, DoubleWritable, Text, DoubleWritable> { private HTable vertexTable; /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#map(java.lang.Object, java.lang.Object, * org.apache.hadoop.mapreduce.Mapper.Context) */ @Override protected void map(Text key, DoubleWritable value, Context context) throws IOException, InterruptedException { Put put = null; String rowKey = Bytes.toString(key.getBytes()).trim(); try { put = new Put(Bytes.toBytes(rowKey)); // set rank value put.add(
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/pagerank/ImportPageRanks.java import java.io.IOException; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.mapreduce.pagerank; /** * Import pageRanks from <code>SeuquenceFile</code> into HBase. * By key => rowKey, value => pageRank. * @author scott_miao */ public class ImportPageRanks extends Configured implements Tool { private static Logger LOGGER = LoggerFactory.getLogger(ImportPageRanks.class); private static class ImportPageRanksMapper extends Mapper<Text, DoubleWritable, Text, DoubleWritable> { private HTable vertexTable; /* * (non-Javadoc) * @see org.apache.hadoop.mapreduce.Mapper#map(java.lang.Object, java.lang.Object, * org.apache.hadoop.mapreduce.Mapper.Context) */ @Override protected void map(Text key, DoubleWritable value, Context context) throws IOException, InterruptedException { Put put = null; String rowKey = Bytes.toString(key.getBytes()).trim(); try { put = new Put(Bytes.toBytes(rowKey)); // set rank value put.add(
Bytes.toBytes(HBaseGraphConstants.HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME),
trendmicro/HGraph
src/main/java/org/trend/hgraph/util/MoveEntities.java
// Path: src/main/java/org/trend/hgraph/util/FindCandidateEntities.java // static boolean isFileExists(String fileName) { // File file = new File(fileName); // if (file.exists()) { // System.err.println("file:" + fileName // + " already exists, pls change to another filepath"); // return true; // } // return false; // }
import static org.trend.hgraph.util.FindCandidateEntities.isFileExists; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.Map.Entry; import java.util.NavigableMap; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.util; /** * @author scott_miao * */ public class MoveEntities extends Configured implements Tool { protected MoveEntities(Configuration conf) { super(conf); } /* (non-Javadoc) * @see org.apache.hadoop.util.Tool#run(java.lang.String[]) */ @Override public int run(String[] args) throws Exception { if (null == args || args.length != 6) { System.err.println("not all 6 options given !!"); printUsage(); return -1; } String vFile = args[0]; String eFile = args[1]; String srcVt = args[2]; String srcEt = args[3]; String destVt = args[4]; String destEt = args[5];
// Path: src/main/java/org/trend/hgraph/util/FindCandidateEntities.java // static boolean isFileExists(String fileName) { // File file = new File(fileName); // if (file.exists()) { // System.err.println("file:" + fileName // + " already exists, pls change to another filepath"); // return true; // } // return false; // } // Path: src/main/java/org/trend/hgraph/util/MoveEntities.java import static org.trend.hgraph.util.FindCandidateEntities.isFileExists; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.Map.Entry; import java.util.NavigableMap; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trend.hgraph.util; /** * @author scott_miao * */ public class MoveEntities extends Configured implements Tool { protected MoveEntities(Configuration conf) { super(conf); } /* (non-Javadoc) * @see org.apache.hadoop.util.Tool#run(java.lang.String[]) */ @Override public int run(String[] args) throws Exception { if (null == args || args.length != 6) { System.err.println("not all 6 options given !!"); printUsage(); return -1; } String vFile = args[0]; String eFile = args[1]; String srcVt = args[2]; String srcEt = args[3]; String destVt = args[4]; String destEt = args[5];
if (!isFileExists(vFile)) {
trendmicro/HGraph
src/main/java/org/trend/hgraph/mapreduce/lib/input/Driver.java
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // }
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants; import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
System.err.println("-b shall be a numeric value, b:" + cmd); printUsage(); return -1; } } else { System.err.println("Not a defined option:" + cmd); printUsage(); return 1; } } else { if (mustStartIdx < 0) { mustStartIdx = idx; } } } if (mustStartIdx + 2 != args.length) { System.err.println("The must options not satisfied !!"); printUsage(); return 1; } LOGGER.info("start to run " + this.getClass().getName() + " with options:" + Arrays.toString(args)); String tableName = args[mustStartIdx]; String outputPath = args[mustStartIdx + 1]; Configuration conf = this.getConf();
// Path: src/main/java/org/trend/hgraph/HBaseGraphConstants.java // public class HBaseGraphConstants { // // public static final String HBASE_GRAPH_TABLE_VERTEX_NAME_KEY = "hbase.graph.table.vertex.name"; // // public static final String HBASE_GRAPH_TABLE_EDGE_NAME_KEY = "hbase.graph.table.edge.name"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME = "property"; // // public static final String HBASE_GRAPH_TABLE_COLFAM_PROPERTY_NAME_DELIMITER = "@"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_1 = "-->"; // // public static final String HBASE_GRAPH_TABLE_EDGE_DELIMITER_2 = "-->"; // } // Path: src/main/java/org/trend/hgraph/mapreduce/lib/input/Driver.java import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.trend.hgraph.HBaseGraphConstants; import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; System.err.println("-b shall be a numeric value, b:" + cmd); printUsage(); return -1; } } else { System.err.println("Not a defined option:" + cmd); printUsage(); return 1; } } else { if (mustStartIdx < 0) { mustStartIdx = idx; } } } if (mustStartIdx + 2 != args.length) { System.err.println("The must options not satisfied !!"); printUsage(); return 1; } LOGGER.info("start to run " + this.getClass().getName() + " with options:" + Arrays.toString(args)); String tableName = args[mustStartIdx]; String outputPath = args[mustStartIdx + 1]; Configuration conf = this.getConf();
LOGGER.info(HBaseGraphConstants.HBASE_GRAPH_TABLE_VERTEX_NAME_KEY + "=" + tableName);
vorburger/SwissKnightMinecraft
SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/logo/LogoPlugin.java
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/command/AbstractPluginWithCommands.java // public abstract class AbstractPluginWithCommands extends AbstractHotPlugin { // // protected @Inject PluginContainer plugin; // // private @Inject AnnotatedCommandManager commandManager; // // protected void onServerStarting() { // } // // protected void onServerStopping() { // } // // @Override // @Listener // public final void onServerStarting(GameStartingServerEvent event) { // super.onServerStarting(event); // commandManager.register(plugin, this); // onServerStarting(); // } // // @Override // @Listener // public final void onServerStopping(GameStoppingServerEvent event) { // super.onServerStopping(event); // commandManager.unregisterAll(); // onServerStopping(); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/MinecraftHelperException.java // public class MinecraftHelperException extends Exception { // private static final long serialVersionUID = 1; // // public MinecraftHelperException(String message) { // super(message); // } // // public MinecraftHelperException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/SpawnHelper.java // public class SpawnHelper { // private final static Logger logger = LoggerFactory.getLogger(SpawnHelper.class); // // private Map<Class<? extends Entity>, EntityType> entityClassToTypeMap; // // protected void populateNewEntityClassToTypeMap(Map<Class<? extends Entity>, EntityType> map) { // map.put(Human.class, EntityTypes.HUMAN); // map.put(Pig.class, EntityTypes.PIG); // } // // // LNE = Log, but Never Exception. Returns Optional instead. // public <T extends Entity> Optional<T> spawnLNE(Class<T> entityClass, Location<World> startingLocation) { // try { // return Optional.of(spawn(entityClass, startingLocation)); // } catch (MinecraftHelperException e) { // logger.error(e.getMessage(), e); // return Optional.empty(); // } // } // // public <T extends Entity> T spawn(Class<T> entityClass, Location<World> location) throws MinecraftHelperException { // EntityType entityType = getEntityType(entityClass); // EntityUniverse entityUniverse = location.getExtent(); // Optional<Entity> optionalEntity = entityUniverse.createEntity(entityType, location.getPosition()); // if (optionalEntity.isPresent()) { // @SuppressWarnings("unchecked") T newEntity = (T) optionalEntity.get(); // boolean isSpawned = entityUniverse.spawnEntity(newEntity, null /* Cause.empty() */); // if (!isSpawned) // throw new MinecraftHelperException("Could not spawn new Entity: " + entityType.getName()); // return newEntity; // } else { // throw new MinecraftHelperException("Could not create new Entity: " + entityType.getName()); // } // } // // protected <T extends Entity> EntityType getEntityType(Class<T> entityClass) throws MinecraftHelperException { // Optional<EntityType> optionalEntityType = getEntityTypeOptional(entityClass); // if (!optionalEntityType.isPresent()) { // throw new MinecraftHelperException("EntityType not found for entityClass: " + entityClass.getName()); // } // EntityType entityType = optionalEntityType.get(); // // TODO isAssignable.. // // if (!entityType.getEntityClass().equals(entityClass)) { // // throw new MinecraftHelperException("EntityType " + entityType.getName() + "'s entityClass " + entityType.getEntityClass() + " != " + entityClass); // // } // return entityType; // } // // protected <T extends Entity> Optional<EntityType> getEntityTypeOptional(Class<T> entityClass) { // return Optional.ofNullable(getEntityClassToTypeMap().get(entityClass)); // } // // protected <T extends Entity> Map<Class<? extends Entity>, EntityType> getEntityClassToTypeMap() { // if (entityClassToTypeMap == null) { // Map<Class<? extends Entity>, EntityType> newEntityClassToTypeMap = new HashMap<>(70); // populateNewEntityClassToTypeMap(newEntityClassToTypeMap); // entityClassToTypeMap = newEntityClassToTypeMap; // } // return entityClassToTypeMap; // } // // }
import java.util.Map; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.api.command.source.LocatedSource; import org.spongepowered.api.entity.living.Human; import com.google.common.collect.MapMaker; import ch.vorburger.minecraft.command.AbstractPluginWithCommands; import ch.vorburger.minecraft.command.Command; import ch.vorburger.minecraft.utils.MinecraftHelperException; import ch.vorburger.minecraft.utils.SpawnHelper;
package ch.vorburger.minecraft.logo; // @Plugin(id = "ch.vorburger.minecraft.logo", name = "LOGO", description="Logo-like commands (thank you, Seymour Papert)", version = "1.0") public class LogoPlugin extends AbstractPluginWithCommands { private final static Logger logger = LoggerFactory.getLogger(LogoPlugin.class); Map<LocatedSource, TurtleImpl> playerTurtleMap = new MapMaker().makeMap();
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/command/AbstractPluginWithCommands.java // public abstract class AbstractPluginWithCommands extends AbstractHotPlugin { // // protected @Inject PluginContainer plugin; // // private @Inject AnnotatedCommandManager commandManager; // // protected void onServerStarting() { // } // // protected void onServerStopping() { // } // // @Override // @Listener // public final void onServerStarting(GameStartingServerEvent event) { // super.onServerStarting(event); // commandManager.register(plugin, this); // onServerStarting(); // } // // @Override // @Listener // public final void onServerStopping(GameStoppingServerEvent event) { // super.onServerStopping(event); // commandManager.unregisterAll(); // onServerStopping(); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/MinecraftHelperException.java // public class MinecraftHelperException extends Exception { // private static final long serialVersionUID = 1; // // public MinecraftHelperException(String message) { // super(message); // } // // public MinecraftHelperException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/SpawnHelper.java // public class SpawnHelper { // private final static Logger logger = LoggerFactory.getLogger(SpawnHelper.class); // // private Map<Class<? extends Entity>, EntityType> entityClassToTypeMap; // // protected void populateNewEntityClassToTypeMap(Map<Class<? extends Entity>, EntityType> map) { // map.put(Human.class, EntityTypes.HUMAN); // map.put(Pig.class, EntityTypes.PIG); // } // // // LNE = Log, but Never Exception. Returns Optional instead. // public <T extends Entity> Optional<T> spawnLNE(Class<T> entityClass, Location<World> startingLocation) { // try { // return Optional.of(spawn(entityClass, startingLocation)); // } catch (MinecraftHelperException e) { // logger.error(e.getMessage(), e); // return Optional.empty(); // } // } // // public <T extends Entity> T spawn(Class<T> entityClass, Location<World> location) throws MinecraftHelperException { // EntityType entityType = getEntityType(entityClass); // EntityUniverse entityUniverse = location.getExtent(); // Optional<Entity> optionalEntity = entityUniverse.createEntity(entityType, location.getPosition()); // if (optionalEntity.isPresent()) { // @SuppressWarnings("unchecked") T newEntity = (T) optionalEntity.get(); // boolean isSpawned = entityUniverse.spawnEntity(newEntity, null /* Cause.empty() */); // if (!isSpawned) // throw new MinecraftHelperException("Could not spawn new Entity: " + entityType.getName()); // return newEntity; // } else { // throw new MinecraftHelperException("Could not create new Entity: " + entityType.getName()); // } // } // // protected <T extends Entity> EntityType getEntityType(Class<T> entityClass) throws MinecraftHelperException { // Optional<EntityType> optionalEntityType = getEntityTypeOptional(entityClass); // if (!optionalEntityType.isPresent()) { // throw new MinecraftHelperException("EntityType not found for entityClass: " + entityClass.getName()); // } // EntityType entityType = optionalEntityType.get(); // // TODO isAssignable.. // // if (!entityType.getEntityClass().equals(entityClass)) { // // throw new MinecraftHelperException("EntityType " + entityType.getName() + "'s entityClass " + entityType.getEntityClass() + " != " + entityClass); // // } // return entityType; // } // // protected <T extends Entity> Optional<EntityType> getEntityTypeOptional(Class<T> entityClass) { // return Optional.ofNullable(getEntityClassToTypeMap().get(entityClass)); // } // // protected <T extends Entity> Map<Class<? extends Entity>, EntityType> getEntityClassToTypeMap() { // if (entityClassToTypeMap == null) { // Map<Class<? extends Entity>, EntityType> newEntityClassToTypeMap = new HashMap<>(70); // populateNewEntityClassToTypeMap(newEntityClassToTypeMap); // entityClassToTypeMap = newEntityClassToTypeMap; // } // return entityClassToTypeMap; // } // // } // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/logo/LogoPlugin.java import java.util.Map; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.api.command.source.LocatedSource; import org.spongepowered.api.entity.living.Human; import com.google.common.collect.MapMaker; import ch.vorburger.minecraft.command.AbstractPluginWithCommands; import ch.vorburger.minecraft.command.Command; import ch.vorburger.minecraft.utils.MinecraftHelperException; import ch.vorburger.minecraft.utils.SpawnHelper; package ch.vorburger.minecraft.logo; // @Plugin(id = "ch.vorburger.minecraft.logo", name = "LOGO", description="Logo-like commands (thank you, Seymour Papert)", version = "1.0") public class LogoPlugin extends AbstractPluginWithCommands { private final static Logger logger = LoggerFactory.getLogger(LogoPlugin.class); Map<LocatedSource, TurtleImpl> playerTurtleMap = new MapMaker().makeMap();
SpawnHelper spawnHelper = new SpawnHelper();
vorburger/SwissKnightMinecraft
SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/logo/LogoPlugin.java
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/command/AbstractPluginWithCommands.java // public abstract class AbstractPluginWithCommands extends AbstractHotPlugin { // // protected @Inject PluginContainer plugin; // // private @Inject AnnotatedCommandManager commandManager; // // protected void onServerStarting() { // } // // protected void onServerStopping() { // } // // @Override // @Listener // public final void onServerStarting(GameStartingServerEvent event) { // super.onServerStarting(event); // commandManager.register(plugin, this); // onServerStarting(); // } // // @Override // @Listener // public final void onServerStopping(GameStoppingServerEvent event) { // super.onServerStopping(event); // commandManager.unregisterAll(); // onServerStopping(); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/MinecraftHelperException.java // public class MinecraftHelperException extends Exception { // private static final long serialVersionUID = 1; // // public MinecraftHelperException(String message) { // super(message); // } // // public MinecraftHelperException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/SpawnHelper.java // public class SpawnHelper { // private final static Logger logger = LoggerFactory.getLogger(SpawnHelper.class); // // private Map<Class<? extends Entity>, EntityType> entityClassToTypeMap; // // protected void populateNewEntityClassToTypeMap(Map<Class<? extends Entity>, EntityType> map) { // map.put(Human.class, EntityTypes.HUMAN); // map.put(Pig.class, EntityTypes.PIG); // } // // // LNE = Log, but Never Exception. Returns Optional instead. // public <T extends Entity> Optional<T> spawnLNE(Class<T> entityClass, Location<World> startingLocation) { // try { // return Optional.of(spawn(entityClass, startingLocation)); // } catch (MinecraftHelperException e) { // logger.error(e.getMessage(), e); // return Optional.empty(); // } // } // // public <T extends Entity> T spawn(Class<T> entityClass, Location<World> location) throws MinecraftHelperException { // EntityType entityType = getEntityType(entityClass); // EntityUniverse entityUniverse = location.getExtent(); // Optional<Entity> optionalEntity = entityUniverse.createEntity(entityType, location.getPosition()); // if (optionalEntity.isPresent()) { // @SuppressWarnings("unchecked") T newEntity = (T) optionalEntity.get(); // boolean isSpawned = entityUniverse.spawnEntity(newEntity, null /* Cause.empty() */); // if (!isSpawned) // throw new MinecraftHelperException("Could not spawn new Entity: " + entityType.getName()); // return newEntity; // } else { // throw new MinecraftHelperException("Could not create new Entity: " + entityType.getName()); // } // } // // protected <T extends Entity> EntityType getEntityType(Class<T> entityClass) throws MinecraftHelperException { // Optional<EntityType> optionalEntityType = getEntityTypeOptional(entityClass); // if (!optionalEntityType.isPresent()) { // throw new MinecraftHelperException("EntityType not found for entityClass: " + entityClass.getName()); // } // EntityType entityType = optionalEntityType.get(); // // TODO isAssignable.. // // if (!entityType.getEntityClass().equals(entityClass)) { // // throw new MinecraftHelperException("EntityType " + entityType.getName() + "'s entityClass " + entityType.getEntityClass() + " != " + entityClass); // // } // return entityType; // } // // protected <T extends Entity> Optional<EntityType> getEntityTypeOptional(Class<T> entityClass) { // return Optional.ofNullable(getEntityClassToTypeMap().get(entityClass)); // } // // protected <T extends Entity> Map<Class<? extends Entity>, EntityType> getEntityClassToTypeMap() { // if (entityClassToTypeMap == null) { // Map<Class<? extends Entity>, EntityType> newEntityClassToTypeMap = new HashMap<>(70); // populateNewEntityClassToTypeMap(newEntityClassToTypeMap); // entityClassToTypeMap = newEntityClassToTypeMap; // } // return entityClassToTypeMap; // } // // }
import java.util.Map; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.api.command.source.LocatedSource; import org.spongepowered.api.entity.living.Human; import com.google.common.collect.MapMaker; import ch.vorburger.minecraft.command.AbstractPluginWithCommands; import ch.vorburger.minecraft.command.Command; import ch.vorburger.minecraft.utils.MinecraftHelperException; import ch.vorburger.minecraft.utils.SpawnHelper;
} @Command("Make Turtle remove block") public void rm(LocatedSource player) { getTurtle(player).remove(); } // @Command("Make Turtle interact") // public void inter(Player player) { // getTurtle(player).interact(); // } // @Command("Make Turtle dig") // public void dig(LocatedSource player) { // getTurtle(player).dig(); // } protected TurtleImpl getTurtle(LocatedSource source) { return playerTurtleMap.computeIfAbsent(source, new Function<LocatedSource, TurtleImpl>() { @Override public TurtleImpl apply(LocatedSource t) { try { Human turtleEntity = spawnHelper.spawn(Human.class, t.getLocation()); // turtleEntity.offer(Keys.CAN_FLY, true); // turtleEntity.offer(Keys.IS_FLYING, true); // turtleEntity.offer(Keys.FLYING_SPEED, 0.0); logger.info("Couldn't find Seymour Human Companion, so spawned a new one at: " + turtleEntity.getLocation().toString()); return new EntityConnectedTurtle(turtleEntity, t);
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/command/AbstractPluginWithCommands.java // public abstract class AbstractPluginWithCommands extends AbstractHotPlugin { // // protected @Inject PluginContainer plugin; // // private @Inject AnnotatedCommandManager commandManager; // // protected void onServerStarting() { // } // // protected void onServerStopping() { // } // // @Override // @Listener // public final void onServerStarting(GameStartingServerEvent event) { // super.onServerStarting(event); // commandManager.register(plugin, this); // onServerStarting(); // } // // @Override // @Listener // public final void onServerStopping(GameStoppingServerEvent event) { // super.onServerStopping(event); // commandManager.unregisterAll(); // onServerStopping(); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/MinecraftHelperException.java // public class MinecraftHelperException extends Exception { // private static final long serialVersionUID = 1; // // public MinecraftHelperException(String message) { // super(message); // } // // public MinecraftHelperException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/SpawnHelper.java // public class SpawnHelper { // private final static Logger logger = LoggerFactory.getLogger(SpawnHelper.class); // // private Map<Class<? extends Entity>, EntityType> entityClassToTypeMap; // // protected void populateNewEntityClassToTypeMap(Map<Class<? extends Entity>, EntityType> map) { // map.put(Human.class, EntityTypes.HUMAN); // map.put(Pig.class, EntityTypes.PIG); // } // // // LNE = Log, but Never Exception. Returns Optional instead. // public <T extends Entity> Optional<T> spawnLNE(Class<T> entityClass, Location<World> startingLocation) { // try { // return Optional.of(spawn(entityClass, startingLocation)); // } catch (MinecraftHelperException e) { // logger.error(e.getMessage(), e); // return Optional.empty(); // } // } // // public <T extends Entity> T spawn(Class<T> entityClass, Location<World> location) throws MinecraftHelperException { // EntityType entityType = getEntityType(entityClass); // EntityUniverse entityUniverse = location.getExtent(); // Optional<Entity> optionalEntity = entityUniverse.createEntity(entityType, location.getPosition()); // if (optionalEntity.isPresent()) { // @SuppressWarnings("unchecked") T newEntity = (T) optionalEntity.get(); // boolean isSpawned = entityUniverse.spawnEntity(newEntity, null /* Cause.empty() */); // if (!isSpawned) // throw new MinecraftHelperException("Could not spawn new Entity: " + entityType.getName()); // return newEntity; // } else { // throw new MinecraftHelperException("Could not create new Entity: " + entityType.getName()); // } // } // // protected <T extends Entity> EntityType getEntityType(Class<T> entityClass) throws MinecraftHelperException { // Optional<EntityType> optionalEntityType = getEntityTypeOptional(entityClass); // if (!optionalEntityType.isPresent()) { // throw new MinecraftHelperException("EntityType not found for entityClass: " + entityClass.getName()); // } // EntityType entityType = optionalEntityType.get(); // // TODO isAssignable.. // // if (!entityType.getEntityClass().equals(entityClass)) { // // throw new MinecraftHelperException("EntityType " + entityType.getName() + "'s entityClass " + entityType.getEntityClass() + " != " + entityClass); // // } // return entityType; // } // // protected <T extends Entity> Optional<EntityType> getEntityTypeOptional(Class<T> entityClass) { // return Optional.ofNullable(getEntityClassToTypeMap().get(entityClass)); // } // // protected <T extends Entity> Map<Class<? extends Entity>, EntityType> getEntityClassToTypeMap() { // if (entityClassToTypeMap == null) { // Map<Class<? extends Entity>, EntityType> newEntityClassToTypeMap = new HashMap<>(70); // populateNewEntityClassToTypeMap(newEntityClassToTypeMap); // entityClassToTypeMap = newEntityClassToTypeMap; // } // return entityClassToTypeMap; // } // // } // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/logo/LogoPlugin.java import java.util.Map; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.api.command.source.LocatedSource; import org.spongepowered.api.entity.living.Human; import com.google.common.collect.MapMaker; import ch.vorburger.minecraft.command.AbstractPluginWithCommands; import ch.vorburger.minecraft.command.Command; import ch.vorburger.minecraft.utils.MinecraftHelperException; import ch.vorburger.minecraft.utils.SpawnHelper; } @Command("Make Turtle remove block") public void rm(LocatedSource player) { getTurtle(player).remove(); } // @Command("Make Turtle interact") // public void inter(Player player) { // getTurtle(player).interact(); // } // @Command("Make Turtle dig") // public void dig(LocatedSource player) { // getTurtle(player).dig(); // } protected TurtleImpl getTurtle(LocatedSource source) { return playerTurtleMap.computeIfAbsent(source, new Function<LocatedSource, TurtleImpl>() { @Override public TurtleImpl apply(LocatedSource t) { try { Human turtleEntity = spawnHelper.spawn(Human.class, t.getLocation()); // turtleEntity.offer(Keys.CAN_FLY, true); // turtleEntity.offer(Keys.IS_FLYING, true); // turtleEntity.offer(Keys.FLYING_SPEED, 0.0); logger.info("Couldn't find Seymour Human Companion, so spawned a new one at: " + turtleEntity.getLocation().toString()); return new EntityConnectedTurtle(turtleEntity, t);
} catch (MinecraftHelperException e) {
vorburger/SwissKnightMinecraft
CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/Downloader.java
// Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/CurseManifest.java // public static class CurseManifestFile { // public int projectID; // public int fileID; // public boolean required; // // @Override // public String toString() { // return "CurseManifestFile [projectID=" + projectID + ", fileID=" + fileID + ", required=" + required + "]"; // } // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.apache.ApacheHttpTransport; import ch.vorburger.minecraft.cursedl.CurseManifest.CurseManifestFile;
package ch.vorburger.minecraft.cursedl; /** * Download files from Curse.com. * * @author Michael Vorburger.ch */ public class Downloader { protected HttpTransport http = new ApacheHttpTransport(); protected HttpRequestFactory requestFactory = http.createRequestFactory(); protected File dir; public Downloader(File directory) { this.dir = directory; } public void download(CurseManifest mf) throws IOException { int i = 1; log("Downloading " + mf.files.size() + " mods into " + dir + " ...");
// Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/CurseManifest.java // public static class CurseManifestFile { // public int projectID; // public int fileID; // public boolean required; // // @Override // public String toString() { // return "CurseManifestFile [projectID=" + projectID + ", fileID=" + fileID + ", required=" + required + "]"; // } // } // Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/Downloader.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.apache.ApacheHttpTransport; import ch.vorburger.minecraft.cursedl.CurseManifest.CurseManifestFile; package ch.vorburger.minecraft.cursedl; /** * Download files from Curse.com. * * @author Michael Vorburger.ch */ public class Downloader { protected HttpTransport http = new ApacheHttpTransport(); protected HttpRequestFactory requestFactory = http.createRequestFactory(); protected File dir; public Downloader(File directory) { this.dir = directory; } public void download(CurseManifest mf) throws IOException { int i = 1; log("Downloading " + mf.files.size() + " mods into " + dir + " ...");
for (CurseManifestFile file : mf.files) {
vorburger/SwissKnightMinecraft
SpongePowered/SpongeTests/src/test/java/ch/vorburger/minecraft/testsinfra/CommandTestHelperTest.java
// Path: SpongePowered/SpongeTests/src/main/java/ch/vorburger/minecraft/testsinfra/CommandTestHelper.java // public static interface Chat { // List<Text> getMessages(); // }
import static org.junit.Assert.assertEquals; import java.util.Collections; import org.junit.Test; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.Texts; import org.spongepowered.api.text.translation.FixedTranslation; import org.spongepowered.api.util.command.CommandResult; import org.spongepowered.common.text.format.SpongeTextStyle; import ch.vorburger.minecraft.testsinfra.CommandTestHelper.Chat; import net.minecraft.util.EnumChatFormatting;
package ch.vorburger.minecraft.testsinfra; public class CommandTestHelperTest { @Test public void textToString() { Text text = Texts.of("something"); assertEquals("something", new CommandTestHelper(null).toString(text)); } @Test public void translatedTextToString() { Text text = Texts.builder(new FixedTranslation("something")).build(); assertEquals("something", new CommandTestHelper(null).toString(text)); } @Test public void chatToString() {
// Path: SpongePowered/SpongeTests/src/main/java/ch/vorburger/minecraft/testsinfra/CommandTestHelper.java // public static interface Chat { // List<Text> getMessages(); // } // Path: SpongePowered/SpongeTests/src/test/java/ch/vorburger/minecraft/testsinfra/CommandTestHelperTest.java import static org.junit.Assert.assertEquals; import java.util.Collections; import org.junit.Test; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.Texts; import org.spongepowered.api.text.translation.FixedTranslation; import org.spongepowered.api.util.command.CommandResult; import org.spongepowered.common.text.format.SpongeTextStyle; import ch.vorburger.minecraft.testsinfra.CommandTestHelper.Chat; import net.minecraft.util.EnumChatFormatting; package ch.vorburger.minecraft.testsinfra; public class CommandTestHelperTest { @Test public void textToString() { Text text = Texts.of("something"); assertEquals("something", new CommandTestHelper(null).toString(text)); } @Test public void translatedTextToString() { Text text = Texts.builder(new FixedTranslation("something")).build(); assertEquals("something", new CommandTestHelper(null).toString(text)); } @Test public void chatToString() {
Chat chat = () -> Collections.singletonList(Texts.of("something"));
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/examples/AdditionLearnlet.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Evaluation.java // public class Evaluation { // // private final boolean correct; // // public Evaluation(boolean correct) { // this.correct = correct; // } // // public boolean isCorrect() { // return correct; // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Learnlet.java // public interface Learnlet { // // Question newQuestion(int level /* TODO , Locale locale */); // // Evaluation answerFreeTextQuestion(Question question, String answer); // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Question.java // public interface Question { // // String getText(Locale locale); // // }
import java.util.Locale; import org.eclipse.jdt.annotation.NonNull; import ch.vorburger.learnlet.Evaluation; import ch.vorburger.learnlet.Learnlet; import ch.vorburger.learnlet.Question;
package ch.vorburger.learnlet.examples; public class AdditionLearnlet implements Learnlet { @Override
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Evaluation.java // public class Evaluation { // // private final boolean correct; // // public Evaluation(boolean correct) { // this.correct = correct; // } // // public boolean isCorrect() { // return correct; // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Learnlet.java // public interface Learnlet { // // Question newQuestion(int level /* TODO , Locale locale */); // // Evaluation answerFreeTextQuestion(Question question, String answer); // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Question.java // public interface Question { // // String getText(Locale locale); // // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/examples/AdditionLearnlet.java import java.util.Locale; import org.eclipse.jdt.annotation.NonNull; import ch.vorburger.learnlet.Evaluation; import ch.vorburger.learnlet.Learnlet; import ch.vorburger.learnlet.Question; package ch.vorburger.learnlet.examples; public class AdditionLearnlet implements Learnlet { @Override
public Question newQuestion(int level) {
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/examples/AdditionLearnlet.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Evaluation.java // public class Evaluation { // // private final boolean correct; // // public Evaluation(boolean correct) { // this.correct = correct; // } // // public boolean isCorrect() { // return correct; // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Learnlet.java // public interface Learnlet { // // Question newQuestion(int level /* TODO , Locale locale */); // // Evaluation answerFreeTextQuestion(Question question, String answer); // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Question.java // public interface Question { // // String getText(Locale locale); // // }
import java.util.Locale; import org.eclipse.jdt.annotation.NonNull; import ch.vorburger.learnlet.Evaluation; import ch.vorburger.learnlet.Learnlet; import ch.vorburger.learnlet.Question;
package ch.vorburger.learnlet.examples; public class AdditionLearnlet implements Learnlet { @Override public Question newQuestion(int level) { // TODO helper to partition difficulties if (level < 3) { level = 3; } else { // max. level = 10; } // TODO random helper; http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range int a = 1; int b = 1; AdditionQuestion q = new AdditionQuestion(); q.a = a; q.b = b; return q; } @Override
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Evaluation.java // public class Evaluation { // // private final boolean correct; // // public Evaluation(boolean correct) { // this.correct = correct; // } // // public boolean isCorrect() { // return correct; // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Learnlet.java // public interface Learnlet { // // Question newQuestion(int level /* TODO , Locale locale */); // // Evaluation answerFreeTextQuestion(Question question, String answer); // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/Question.java // public interface Question { // // String getText(Locale locale); // // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learnlet/examples/AdditionLearnlet.java import java.util.Locale; import org.eclipse.jdt.annotation.NonNull; import ch.vorburger.learnlet.Evaluation; import ch.vorburger.learnlet.Learnlet; import ch.vorburger.learnlet.Question; package ch.vorburger.learnlet.examples; public class AdditionLearnlet implements Learnlet { @Override public Question newQuestion(int level) { // TODO helper to partition difficulties if (level < 3) { level = 3; } else { // max. level = 10; } // TODO random helper; http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range int a = 1; int b = 1; AdditionQuestion q = new AdditionQuestion(); q.a = a; q.b = b; return q; } @Override
public Evaluation answerFreeTextQuestion(Question question, String answer) {
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // }
import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID;
package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID; package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override
public ServiceQuestion newQuestion(UserID uid) {
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // }
import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID;
package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID; package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override
public ServiceQuestion newQuestion(UserID uid) {
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // }
import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID;
package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override public ServiceQuestion newQuestion(UserID uid) { // TODO this needs to go into the AdditionLearnlet return new ServiceQuestion("1", "What is 1 + 1?"); } @Override
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID; package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override public ServiceQuestion newQuestion(UserID uid) { // TODO this needs to go into the AdditionLearnlet return new ServiceQuestion("1", "What is 1 + 1?"); } @Override
public ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException {
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // }
import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID;
package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override public ServiceQuestion newQuestion(UserID uid) { // TODO this needs to go into the AdditionLearnlet return new ServiceQuestion("1", "What is 1 + 1?"); } @Override
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceEvaluation.java // public class ServiceEvaluation { // // TODO https://immutables.github.io // // private final boolean correct; // private final int totalScore; // private final Optional<String> comment; // private final Optional<String> url; // // public ServiceEvaluation(boolean correct, int totalScore) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.empty(); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.empty(); // } // // public ServiceEvaluation(boolean correct, int totalScore, String comment, String url) { // this.correct = correct; // this.totalScore = totalScore; // this.comment = Optional.of(comment); // this.url = Optional.of(url); // } // // public boolean isCorrect() { // return correct; // } // // public int getTotalScore() { // return totalScore; // } // // public Optional<String> getComment() { // return comment; // } // // public Optional<String> getURL() { // return url; // } // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningService.java // public interface LearningService { // // ServiceQuestion newQuestion(UserID uid) throws LearningServiceException; // // ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException; // // ServiceEvaluation answerMultipleChoiceQuestion(String questionID, int choice) throws LearningServiceException; // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/LearningServiceException.java // public class LearningServiceException extends Exception { // private static final long serialVersionUID = 5426151440815984742L; // // public LearningServiceException(String message) { // super(message); // } // // public LearningServiceException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java // public class ServiceQuestion { // // TODO https://immutables.github.io // // private final String id; // private final String text; // private final List<String> choices; // // /** // * Free text question. // */ // public ServiceQuestion(String id, String text) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.emptyList(); // } // // /** // * Multiple Choice question. // */ // public ServiceQuestion(String id, String text, List<String> choices) { // super(); // this.id = id; // this.text = text; // this.choices = Collections.unmodifiableList(choices); // // if (choices.isEmpty()) // throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); // } // // public String getId() { // return id; // } // // public String getText() { // return text; // } // // public List<String> getChoices() { // return choices; // } // // @Override // public int hashCode() { // return Objects.hash(id, text, choices); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.id, another.id) // && Objects.equals(one.text, another.text) // && Objects.equals(one.choices, another.choices)); // } // // } // // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java // public class UserID { // // TODO https://immutables.github.io // // private final String scheme; // private final String uuid; // // TODO private final Locale locale; // // public UserID(String scheme, String uuid) { // super(); // this.scheme = scheme; // this.uuid = uuid; // } // // public String getScheme() { // return scheme; // } // // public String getUuid() { // return uuid; // } // // @Override // public int hashCode() { // return Objects.hash(scheme, uuid); // } // // @Override // public boolean equals(@Nullable Object other) { // return EvenMoreObjects.equalsHelper(this, other, // (one, another) -> Objects.equals(one.scheme, another.scheme) // && Objects.equals(one.uuid, another.uuid)); // } // // @Override // public String toString() { // return new StringBuilder(scheme).append("::").append(uuid).toString(); // } // // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/server/LearningServiceImpl.java import ch.vorburger.learning.ServiceEvaluation; import ch.vorburger.learning.LearningService; import ch.vorburger.learning.LearningServiceException; import ch.vorburger.learning.ServiceQuestion; import ch.vorburger.learning.UserID; package ch.vorburger.learning.server; public class LearningServiceImpl implements LearningService { @Override public ServiceQuestion newQuestion(UserID uid) { // TODO this needs to go into the AdditionLearnlet return new ServiceQuestion("1", "What is 1 + 1?"); } @Override
public ServiceEvaluation answerFreeTextQuestion(String questionID, String answer) throws LearningServiceException {
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/utils/EvenMoreObjects.java // public final class EvenMoreObjects { // // @SuppressWarnings("unchecked") // public static <T> boolean equalsHelper(T self, @Nullable Object other, BooleanEqualsFunction<T> equals) { // if (other == null) { // return false; // } // if (other == self) { // return true; // } // if (self.getClass() != other.getClass()) { // return false; // } // return equals.apply(self, (T) other); // } // // @FunctionalInterface // public interface BooleanEqualsFunction<T> extends BiFunction<T, T, Boolean> { } // // private EvenMoreObjects() { } // }
import java.util.Collections; import java.util.List; import java.util.Objects; import org.eclipse.jdt.annotation.Nullable; import ch.vorburger.utils.EvenMoreObjects;
*/ public ServiceQuestion(String id, String text, List<String> choices) { super(); this.id = id; this.text = text; this.choices = Collections.unmodifiableList(choices); if (choices.isEmpty()) throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); } public String getId() { return id; } public String getText() { return text; } public List<String> getChoices() { return choices; } @Override public int hashCode() { return Objects.hash(id, text, choices); } @Override public boolean equals(@Nullable Object other) {
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/utils/EvenMoreObjects.java // public final class EvenMoreObjects { // // @SuppressWarnings("unchecked") // public static <T> boolean equalsHelper(T self, @Nullable Object other, BooleanEqualsFunction<T> equals) { // if (other == null) { // return false; // } // if (other == self) { // return true; // } // if (self.getClass() != other.getClass()) { // return false; // } // return equals.apply(self, (T) other); // } // // @FunctionalInterface // public interface BooleanEqualsFunction<T> extends BiFunction<T, T, Boolean> { } // // private EvenMoreObjects() { } // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/ServiceQuestion.java import java.util.Collections; import java.util.List; import java.util.Objects; import org.eclipse.jdt.annotation.Nullable; import ch.vorburger.utils.EvenMoreObjects; */ public ServiceQuestion(String id, String text, List<String> choices) { super(); this.id = id; this.text = text; this.choices = Collections.unmodifiableList(choices); if (choices.isEmpty()) throw new IllegalArgumentException("choices.isEmpty(), so it's a free-text not multiple choice question"); } public String getId() { return id; } public String getText() { return text; } public List<String> getChoices() { return choices; } @Override public int hashCode() { return Objects.hash(id, text, choices); } @Override public boolean equals(@Nullable Object other) {
return EvenMoreObjects.equalsHelper(this, other,
vorburger/SwissKnightMinecraft
SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/MyFirstSpongePlugIn.java
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/SpawnHelper.java // public class SpawnHelper { // private final static Logger logger = LoggerFactory.getLogger(SpawnHelper.class); // // private Map<Class<? extends Entity>, EntityType> entityClassToTypeMap; // // protected void populateNewEntityClassToTypeMap(Map<Class<? extends Entity>, EntityType> map) { // map.put(Human.class, EntityTypes.HUMAN); // map.put(Pig.class, EntityTypes.PIG); // } // // // LNE = Log, but Never Exception. Returns Optional instead. // public <T extends Entity> Optional<T> spawnLNE(Class<T> entityClass, Location<World> startingLocation) { // try { // return Optional.of(spawn(entityClass, startingLocation)); // } catch (MinecraftHelperException e) { // logger.error(e.getMessage(), e); // return Optional.empty(); // } // } // // public <T extends Entity> T spawn(Class<T> entityClass, Location<World> location) throws MinecraftHelperException { // EntityType entityType = getEntityType(entityClass); // EntityUniverse entityUniverse = location.getExtent(); // Optional<Entity> optionalEntity = entityUniverse.createEntity(entityType, location.getPosition()); // if (optionalEntity.isPresent()) { // @SuppressWarnings("unchecked") T newEntity = (T) optionalEntity.get(); // boolean isSpawned = entityUniverse.spawnEntity(newEntity, null /* Cause.empty() */); // if (!isSpawned) // throw new MinecraftHelperException("Could not spawn new Entity: " + entityType.getName()); // return newEntity; // } else { // throw new MinecraftHelperException("Could not create new Entity: " + entityType.getName()); // } // } // // protected <T extends Entity> EntityType getEntityType(Class<T> entityClass) throws MinecraftHelperException { // Optional<EntityType> optionalEntityType = getEntityTypeOptional(entityClass); // if (!optionalEntityType.isPresent()) { // throw new MinecraftHelperException("EntityType not found for entityClass: " + entityClass.getName()); // } // EntityType entityType = optionalEntityType.get(); // // TODO isAssignable.. // // if (!entityType.getEntityClass().equals(entityClass)) { // // throw new MinecraftHelperException("EntityType " + entityType.getName() + "'s entityClass " + entityType.getEntityClass() + " != " + entityClass); // // } // return entityType; // } // // protected <T extends Entity> Optional<EntityType> getEntityTypeOptional(Class<T> entityClass) { // return Optional.ofNullable(getEntityClassToTypeMap().get(entityClass)); // } // // protected <T extends Entity> Map<Class<? extends Entity>, EntityType> getEntityClassToTypeMap() { // if (entityClassToTypeMap == null) { // Map<Class<? extends Entity>, EntityType> newEntityClassToTypeMap = new HashMap<>(70); // populateNewEntityClassToTypeMap(newEntityClassToTypeMap); // entityClassToTypeMap = newEntityClassToTypeMap; // } // return entityClassToTypeMap; // } // // }
import java.util.Optional; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.command.CommandCallable; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.config.DefaultConfig; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameStartingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import com.google.inject.Inject; import ch.vorburger.minecraft.utils.SpawnHelper; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.loader.ConfigurationLoader;
package ch.vorburger.minecraft; // @Plugin(id = "MyFirstSponge", name = "My first Sponge Plug-In", version = "1.0") public class MyFirstSpongePlugIn { @Inject Game game; @Inject Logger logger; @Inject PluginContainer plugin; @DefaultConfig(sharedRoot = true) @Inject ConfigurationLoader<CommentedConfigurationNode> configLoader; Optional<CommandMapping> commandMapping = Optional.empty();
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/utils/SpawnHelper.java // public class SpawnHelper { // private final static Logger logger = LoggerFactory.getLogger(SpawnHelper.class); // // private Map<Class<? extends Entity>, EntityType> entityClassToTypeMap; // // protected void populateNewEntityClassToTypeMap(Map<Class<? extends Entity>, EntityType> map) { // map.put(Human.class, EntityTypes.HUMAN); // map.put(Pig.class, EntityTypes.PIG); // } // // // LNE = Log, but Never Exception. Returns Optional instead. // public <T extends Entity> Optional<T> spawnLNE(Class<T> entityClass, Location<World> startingLocation) { // try { // return Optional.of(spawn(entityClass, startingLocation)); // } catch (MinecraftHelperException e) { // logger.error(e.getMessage(), e); // return Optional.empty(); // } // } // // public <T extends Entity> T spawn(Class<T> entityClass, Location<World> location) throws MinecraftHelperException { // EntityType entityType = getEntityType(entityClass); // EntityUniverse entityUniverse = location.getExtent(); // Optional<Entity> optionalEntity = entityUniverse.createEntity(entityType, location.getPosition()); // if (optionalEntity.isPresent()) { // @SuppressWarnings("unchecked") T newEntity = (T) optionalEntity.get(); // boolean isSpawned = entityUniverse.spawnEntity(newEntity, null /* Cause.empty() */); // if (!isSpawned) // throw new MinecraftHelperException("Could not spawn new Entity: " + entityType.getName()); // return newEntity; // } else { // throw new MinecraftHelperException("Could not create new Entity: " + entityType.getName()); // } // } // // protected <T extends Entity> EntityType getEntityType(Class<T> entityClass) throws MinecraftHelperException { // Optional<EntityType> optionalEntityType = getEntityTypeOptional(entityClass); // if (!optionalEntityType.isPresent()) { // throw new MinecraftHelperException("EntityType not found for entityClass: " + entityClass.getName()); // } // EntityType entityType = optionalEntityType.get(); // // TODO isAssignable.. // // if (!entityType.getEntityClass().equals(entityClass)) { // // throw new MinecraftHelperException("EntityType " + entityType.getName() + "'s entityClass " + entityType.getEntityClass() + " != " + entityClass); // // } // return entityType; // } // // protected <T extends Entity> Optional<EntityType> getEntityTypeOptional(Class<T> entityClass) { // return Optional.ofNullable(getEntityClassToTypeMap().get(entityClass)); // } // // protected <T extends Entity> Map<Class<? extends Entity>, EntityType> getEntityClassToTypeMap() { // if (entityClassToTypeMap == null) { // Map<Class<? extends Entity>, EntityType> newEntityClassToTypeMap = new HashMap<>(70); // populateNewEntityClassToTypeMap(newEntityClassToTypeMap); // entityClassToTypeMap = newEntityClassToTypeMap; // } // return entityClassToTypeMap; // } // // } // Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/MyFirstSpongePlugIn.java import java.util.Optional; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.command.CommandCallable; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.config.DefaultConfig; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameStartingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import com.google.inject.Inject; import ch.vorburger.minecraft.utils.SpawnHelper; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.loader.ConfigurationLoader; package ch.vorburger.minecraft; // @Plugin(id = "MyFirstSponge", name = "My first Sponge Plug-In", version = "1.0") public class MyFirstSpongePlugIn { @Inject Game game; @Inject Logger logger; @Inject PluginContainer plugin; @DefaultConfig(sharedRoot = true) @Inject ConfigurationLoader<CommentedConfigurationNode> configLoader; Optional<CommandMapping> commandMapping = Optional.empty();
SpawnHelper spawnHelper = new SpawnHelper();
vorburger/SwissKnightMinecraft
SpongePowered/MyFirstSpongePlugIn/src/test/java/ch/vorburger/minecraft/command/CommandManagerTest.java
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/command/AnnotatedCommandManager.java // protected static class MethodArg { // String name; // Type type; // boolean optional = false; // boolean vararg = false; // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import org.junit.Ignore; import org.junit.Test; import org.spongepowered.api.command.CommandSource; import ch.vorburger.minecraft.command.AnnotatedCommandManager.MethodArg;
package ch.vorburger.minecraft.command; @Ignore public class CommandManagerTest { @Command void test(CommandSource commandSource, Optional<String> name, int n, String commandToRepeat) { }; @Test public void getCommandElements() throws Exception { Method method = this.getClass().getDeclaredMethod("test", CommandSource.class, Optional.class, Integer.TYPE, String.class);
// Path: SpongePowered/MyFirstSpongePlugIn/src/main/java/ch/vorburger/minecraft/command/AnnotatedCommandManager.java // protected static class MethodArg { // String name; // Type type; // boolean optional = false; // boolean vararg = false; // } // Path: SpongePowered/MyFirstSpongePlugIn/src/test/java/ch/vorburger/minecraft/command/CommandManagerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import org.junit.Ignore; import org.junit.Test; import org.spongepowered.api.command.CommandSource; import ch.vorburger.minecraft.command.AnnotatedCommandManager.MethodArg; package ch.vorburger.minecraft.command; @Ignore public class CommandManagerTest { @Command void test(CommandSource commandSource, Optional<String> name, int n, String commandToRepeat) { }; @Test public void getCommandElements() throws Exception { Method method = this.getClass().getDeclaredMethod("test", CommandSource.class, Optional.class, Integer.TYPE, String.class);
List<MethodArg> methodArgs = new AnnotatedCommandManager().getMethodArgs(method);
vorburger/SwissKnightMinecraft
SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/utils/EvenMoreObjects.java // public final class EvenMoreObjects { // // @SuppressWarnings("unchecked") // public static <T> boolean equalsHelper(T self, @Nullable Object other, BooleanEqualsFunction<T> equals) { // if (other == null) { // return false; // } // if (other == self) { // return true; // } // if (self.getClass() != other.getClass()) { // return false; // } // return equals.apply(self, (T) other); // } // // @FunctionalInterface // public interface BooleanEqualsFunction<T> extends BiFunction<T, T, Boolean> { } // // private EvenMoreObjects() { } // }
import java.util.Objects; import org.eclipse.jdt.annotation.Nullable; import ch.vorburger.utils.EvenMoreObjects;
package ch.vorburger.learning; public class UserID { // TODO https://immutables.github.io private final String scheme; private final String uuid; // TODO private final Locale locale; public UserID(String scheme, String uuid) { super(); this.scheme = scheme; this.uuid = uuid; } public String getScheme() { return scheme; } public String getUuid() { return uuid; } @Override public int hashCode() { return Objects.hash(scheme, uuid); } @Override public boolean equals(@Nullable Object other) {
// Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/utils/EvenMoreObjects.java // public final class EvenMoreObjects { // // @SuppressWarnings("unchecked") // public static <T> boolean equalsHelper(T self, @Nullable Object other, BooleanEqualsFunction<T> equals) { // if (other == null) { // return false; // } // if (other == self) { // return true; // } // if (self.getClass() != other.getClass()) { // return false; // } // return equals.apply(self, (T) other); // } // // @FunctionalInterface // public interface BooleanEqualsFunction<T> extends BiFunction<T, T, Boolean> { } // // private EvenMoreObjects() { } // } // Path: SpongePowered/ch.vorburger.minecraft.learning/src/main/java/ch/vorburger/learning/UserID.java import java.util.Objects; import org.eclipse.jdt.annotation.Nullable; import ch.vorburger.utils.EvenMoreObjects; package ch.vorburger.learning; public class UserID { // TODO https://immutables.github.io private final String scheme; private final String uuid; // TODO private final Locale locale; public UserID(String scheme, String uuid) { super(); this.scheme = scheme; this.uuid = uuid; } public String getScheme() { return scheme; } public String getUuid() { return uuid; } @Override public int hashCode() { return Objects.hash(scheme, uuid); } @Override public boolean equals(@Nullable Object other) {
return EvenMoreObjects.equalsHelper(this, other,
vorburger/SwissKnightMinecraft
CurseDownloader/src/test/java/ch/vorburger/minecraft/cursedl/tests/CurseDownloaderTest.java
// Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/CurseManifest.java // public class CurseManifest { // // protected static final Gson gson = new Gson(); // // public int projectID; // public List<CurseManifestFile> files = new ArrayList<CurseManifestFile>(); // // public static CurseManifest fromFile(File file) throws IOException { // return fromString(Files.toString(file, Charsets.UTF_8)); // } // // public static CurseManifest fromString(String json) { // return gson.fromJson(json, CurseManifest.class); // } // // private CurseManifest() { // } // // public List<CurseManifestFile> getFiles() { // return files; // } // // public static class CurseManifestFile { // public int projectID; // public int fileID; // public boolean required; // // @Override // public String toString() { // return "CurseManifestFile [projectID=" + projectID + ", fileID=" + fileID + ", required=" + required + "]"; // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("projectID", projectID) // .add("files", files) // .toString(); // } // // } // // Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/Downloader.java // public class Downloader { // // protected HttpTransport http = new ApacheHttpTransport(); // protected HttpRequestFactory requestFactory = http.createRequestFactory(); // // protected File dir; // // public Downloader(File directory) { // this.dir = directory; // } // // public void download(CurseManifest mf) throws IOException { // int i = 1; // log("Downloading " + mf.files.size() + " mods into " + dir + " ..."); // for (CurseManifestFile file : mf.files) { // // TODO Parallelize! // log(i + ". downloading projectID: " + file.projectID + ", fileID: " + file.fileID + " .."); // download(file.projectID, file.fileID); // ++i; // } // } // // public void download(int projectID, int fileID) throws IOException { // GenericUrl projectURL = new GenericUrl("http://minecraft.curseforge.com/projects/" + projectID); // HttpRequest projectRequest = requestFactory.buildGetRequest(projectURL); // // This will redirect - the point of this is just to obtain the new URL! // HttpResponse projectResponse = projectRequest.execute(); // projectResponse.disconnect(); // // GenericUrl newURL = projectResponse.getRequest().getUrl(); // newURL.appendRawPath("/files/" + fileID + "/download"); // try { // download(newURL); // } catch (HttpResponseException e) { // // TODO Return this, instead of only logging // log("FAILED to download "+ newURL + "; you should manually download another version of this mod from " + projectURL); // } // } // // protected void download(GenericUrl newURL) throws IOException { // HttpRequest downloadRequest = requestFactory.buildGetRequest(newURL); // HttpResponse response = null; // try { // response = downloadRequest.execute(); // // List<String> pathParts = response.getRequest().getUrl().getPathParts(); // String fileName = pathParts.get(pathParts.size() - 1); // TODO tail // File dlFile = new File(dir, fileName); // try (OutputStream outputStream = new FileOutputStream(dlFile)) { // response.download(outputStream); // } // log("Successfully downloaded: " + dlFile.getName()); // // } finally { // if (response != null) // response.disconnect(); // } // } // // protected void log(String msg) { // System.out.println(msg); // } // // }
import java.net.URL; import org.junit.Ignore; import org.junit.Test; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.common.io.Resources; import ch.vorburger.minecraft.cursedl.CurseManifest; import ch.vorburger.minecraft.cursedl.Downloader;
package ch.vorburger.minecraft.cursedl.tests; public class CurseDownloaderTest { @Test public void testDownloadOneFile() throws Exception {
// Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/CurseManifest.java // public class CurseManifest { // // protected static final Gson gson = new Gson(); // // public int projectID; // public List<CurseManifestFile> files = new ArrayList<CurseManifestFile>(); // // public static CurseManifest fromFile(File file) throws IOException { // return fromString(Files.toString(file, Charsets.UTF_8)); // } // // public static CurseManifest fromString(String json) { // return gson.fromJson(json, CurseManifest.class); // } // // private CurseManifest() { // } // // public List<CurseManifestFile> getFiles() { // return files; // } // // public static class CurseManifestFile { // public int projectID; // public int fileID; // public boolean required; // // @Override // public String toString() { // return "CurseManifestFile [projectID=" + projectID + ", fileID=" + fileID + ", required=" + required + "]"; // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("projectID", projectID) // .add("files", files) // .toString(); // } // // } // // Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/Downloader.java // public class Downloader { // // protected HttpTransport http = new ApacheHttpTransport(); // protected HttpRequestFactory requestFactory = http.createRequestFactory(); // // protected File dir; // // public Downloader(File directory) { // this.dir = directory; // } // // public void download(CurseManifest mf) throws IOException { // int i = 1; // log("Downloading " + mf.files.size() + " mods into " + dir + " ..."); // for (CurseManifestFile file : mf.files) { // // TODO Parallelize! // log(i + ". downloading projectID: " + file.projectID + ", fileID: " + file.fileID + " .."); // download(file.projectID, file.fileID); // ++i; // } // } // // public void download(int projectID, int fileID) throws IOException { // GenericUrl projectURL = new GenericUrl("http://minecraft.curseforge.com/projects/" + projectID); // HttpRequest projectRequest = requestFactory.buildGetRequest(projectURL); // // This will redirect - the point of this is just to obtain the new URL! // HttpResponse projectResponse = projectRequest.execute(); // projectResponse.disconnect(); // // GenericUrl newURL = projectResponse.getRequest().getUrl(); // newURL.appendRawPath("/files/" + fileID + "/download"); // try { // download(newURL); // } catch (HttpResponseException e) { // // TODO Return this, instead of only logging // log("FAILED to download "+ newURL + "; you should manually download another version of this mod from " + projectURL); // } // } // // protected void download(GenericUrl newURL) throws IOException { // HttpRequest downloadRequest = requestFactory.buildGetRequest(newURL); // HttpResponse response = null; // try { // response = downloadRequest.execute(); // // List<String> pathParts = response.getRequest().getUrl().getPathParts(); // String fileName = pathParts.get(pathParts.size() - 1); // TODO tail // File dlFile = new File(dir, fileName); // try (OutputStream outputStream = new FileOutputStream(dlFile)) { // response.download(outputStream); // } // log("Successfully downloaded: " + dlFile.getName()); // // } finally { // if (response != null) // response.disconnect(); // } // } // // protected void log(String msg) { // System.out.println(msg); // } // // } // Path: CurseDownloader/src/test/java/ch/vorburger/minecraft/cursedl/tests/CurseDownloaderTest.java import java.net.URL; import org.junit.Ignore; import org.junit.Test; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.common.io.Resources; import ch.vorburger.minecraft.cursedl.CurseManifest; import ch.vorburger.minecraft.cursedl.Downloader; package ch.vorburger.minecraft.cursedl.tests; public class CurseDownloaderTest { @Test public void testDownloadOneFile() throws Exception {
new Downloader(Files.createTempDir()).download(223248, 2237600);
vorburger/SwissKnightMinecraft
CurseDownloader/src/test/java/ch/vorburger/minecraft/cursedl/tests/CurseDownloaderTest.java
// Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/CurseManifest.java // public class CurseManifest { // // protected static final Gson gson = new Gson(); // // public int projectID; // public List<CurseManifestFile> files = new ArrayList<CurseManifestFile>(); // // public static CurseManifest fromFile(File file) throws IOException { // return fromString(Files.toString(file, Charsets.UTF_8)); // } // // public static CurseManifest fromString(String json) { // return gson.fromJson(json, CurseManifest.class); // } // // private CurseManifest() { // } // // public List<CurseManifestFile> getFiles() { // return files; // } // // public static class CurseManifestFile { // public int projectID; // public int fileID; // public boolean required; // // @Override // public String toString() { // return "CurseManifestFile [projectID=" + projectID + ", fileID=" + fileID + ", required=" + required + "]"; // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("projectID", projectID) // .add("files", files) // .toString(); // } // // } // // Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/Downloader.java // public class Downloader { // // protected HttpTransport http = new ApacheHttpTransport(); // protected HttpRequestFactory requestFactory = http.createRequestFactory(); // // protected File dir; // // public Downloader(File directory) { // this.dir = directory; // } // // public void download(CurseManifest mf) throws IOException { // int i = 1; // log("Downloading " + mf.files.size() + " mods into " + dir + " ..."); // for (CurseManifestFile file : mf.files) { // // TODO Parallelize! // log(i + ". downloading projectID: " + file.projectID + ", fileID: " + file.fileID + " .."); // download(file.projectID, file.fileID); // ++i; // } // } // // public void download(int projectID, int fileID) throws IOException { // GenericUrl projectURL = new GenericUrl("http://minecraft.curseforge.com/projects/" + projectID); // HttpRequest projectRequest = requestFactory.buildGetRequest(projectURL); // // This will redirect - the point of this is just to obtain the new URL! // HttpResponse projectResponse = projectRequest.execute(); // projectResponse.disconnect(); // // GenericUrl newURL = projectResponse.getRequest().getUrl(); // newURL.appendRawPath("/files/" + fileID + "/download"); // try { // download(newURL); // } catch (HttpResponseException e) { // // TODO Return this, instead of only logging // log("FAILED to download "+ newURL + "; you should manually download another version of this mod from " + projectURL); // } // } // // protected void download(GenericUrl newURL) throws IOException { // HttpRequest downloadRequest = requestFactory.buildGetRequest(newURL); // HttpResponse response = null; // try { // response = downloadRequest.execute(); // // List<String> pathParts = response.getRequest().getUrl().getPathParts(); // String fileName = pathParts.get(pathParts.size() - 1); // TODO tail // File dlFile = new File(dir, fileName); // try (OutputStream outputStream = new FileOutputStream(dlFile)) { // response.download(outputStream); // } // log("Successfully downloaded: " + dlFile.getName()); // // } finally { // if (response != null) // response.disconnect(); // } // } // // protected void log(String msg) { // System.out.println(msg); // } // // }
import java.net.URL; import org.junit.Ignore; import org.junit.Test; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.common.io.Resources; import ch.vorburger.minecraft.cursedl.CurseManifest; import ch.vorburger.minecraft.cursedl.Downloader;
package ch.vorburger.minecraft.cursedl.tests; public class CurseDownloaderTest { @Test public void testDownloadOneFile() throws Exception { new Downloader(Files.createTempDir()).download(223248, 2237600); } @Test @Ignore public void testCurseDownloader() throws Exception { URL url = Resources.getResource("manifest.json"); String manifest = Resources.toString(url, Charsets.UTF_8);
// Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/CurseManifest.java // public class CurseManifest { // // protected static final Gson gson = new Gson(); // // public int projectID; // public List<CurseManifestFile> files = new ArrayList<CurseManifestFile>(); // // public static CurseManifest fromFile(File file) throws IOException { // return fromString(Files.toString(file, Charsets.UTF_8)); // } // // public static CurseManifest fromString(String json) { // return gson.fromJson(json, CurseManifest.class); // } // // private CurseManifest() { // } // // public List<CurseManifestFile> getFiles() { // return files; // } // // public static class CurseManifestFile { // public int projectID; // public int fileID; // public boolean required; // // @Override // public String toString() { // return "CurseManifestFile [projectID=" + projectID + ", fileID=" + fileID + ", required=" + required + "]"; // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("projectID", projectID) // .add("files", files) // .toString(); // } // // } // // Path: CurseDownloader/src/main/java/ch/vorburger/minecraft/cursedl/Downloader.java // public class Downloader { // // protected HttpTransport http = new ApacheHttpTransport(); // protected HttpRequestFactory requestFactory = http.createRequestFactory(); // // protected File dir; // // public Downloader(File directory) { // this.dir = directory; // } // // public void download(CurseManifest mf) throws IOException { // int i = 1; // log("Downloading " + mf.files.size() + " mods into " + dir + " ..."); // for (CurseManifestFile file : mf.files) { // // TODO Parallelize! // log(i + ". downloading projectID: " + file.projectID + ", fileID: " + file.fileID + " .."); // download(file.projectID, file.fileID); // ++i; // } // } // // public void download(int projectID, int fileID) throws IOException { // GenericUrl projectURL = new GenericUrl("http://minecraft.curseforge.com/projects/" + projectID); // HttpRequest projectRequest = requestFactory.buildGetRequest(projectURL); // // This will redirect - the point of this is just to obtain the new URL! // HttpResponse projectResponse = projectRequest.execute(); // projectResponse.disconnect(); // // GenericUrl newURL = projectResponse.getRequest().getUrl(); // newURL.appendRawPath("/files/" + fileID + "/download"); // try { // download(newURL); // } catch (HttpResponseException e) { // // TODO Return this, instead of only logging // log("FAILED to download "+ newURL + "; you should manually download another version of this mod from " + projectURL); // } // } // // protected void download(GenericUrl newURL) throws IOException { // HttpRequest downloadRequest = requestFactory.buildGetRequest(newURL); // HttpResponse response = null; // try { // response = downloadRequest.execute(); // // List<String> pathParts = response.getRequest().getUrl().getPathParts(); // String fileName = pathParts.get(pathParts.size() - 1); // TODO tail // File dlFile = new File(dir, fileName); // try (OutputStream outputStream = new FileOutputStream(dlFile)) { // response.download(outputStream); // } // log("Successfully downloaded: " + dlFile.getName()); // // } finally { // if (response != null) // response.disconnect(); // } // } // // protected void log(String msg) { // System.out.println(msg); // } // // } // Path: CurseDownloader/src/test/java/ch/vorburger/minecraft/cursedl/tests/CurseDownloaderTest.java import java.net.URL; import org.junit.Ignore; import org.junit.Test; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.common.io.Resources; import ch.vorburger.minecraft.cursedl.CurseManifest; import ch.vorburger.minecraft.cursedl.Downloader; package ch.vorburger.minecraft.cursedl.tests; public class CurseDownloaderTest { @Test public void testDownloadOneFile() throws Exception { new Downloader(Files.createTempDir()).download(223248, 2237600); } @Test @Ignore public void testCurseDownloader() throws Exception { URL url = Resources.getResource("manifest.json"); String manifest = Resources.toString(url, Charsets.UTF_8);
CurseManifest mf = CurseManifest.fromString(manifest);
RatioLabs/BLEService
DeviceService/src/com/ratio/deviceService/BTServiceProfile.java
// Path: DeviceService/src/com/ratio/util/UUIDUtils.java // public class UUIDUtils { // // // if the UUID is null, then we write 0L,0L // public static void writeToParcel(UUID uuid, Parcel parcel) { // if (uuid == null) { // parcel.writeLong(0L); // parcel.writeLong(0L); // } else { // parcel.writeLong(uuid.getLeastSignificantBits()); // parcel.writeLong(uuid.getMostSignificantBits()); // } // } // // // if the uuid is 0L,0L, then we assume that it is null // public static UUID readFromParcel(Parcel parcel) { // long lsb = parcel.readLong(); // long msb = parcel.readLong(); // if ((lsb == 0L) && (msb == 0L)) { // return null; // } else { // return new UUID(msb, lsb); // } // } // // // turn B6981800756211E2B50D00163E46F8FE into B6981800-7562-11E2-B50D-00163E46F8FE // public static UUID fromByteArray(byte[] byteArray, int offset) { // String format = "%s-%s-%s-%s-%s"; // String p1 = StringUtil.toHexCode(byteArray, offset + 0, 4); // String p2 = StringUtil.toHexCode(byteArray, offset + 4, 2); // String p3 = StringUtil.toHexCode(byteArray, offset + 6, 2); // String p4 = StringUtil.toHexCode(byteArray, offset + 8, 2); // String p5 = StringUtil.toHexCode(byteArray, offset + 10, 6); // String uuidString = String.format(format, p1, p2, p3, p4, p5); // return UUID.fromString(uuidString); // } // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.ratio.util.UUIDUtils; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.os.Parcel; import android.os.Parcelable;
package com.ratio.deviceService; /** * external description of a device profile, so once we query the device services and characteristics * we can send it back from the service to the activity in a bundle, which can be received by the BroadcastReceiver * @author mreynolds * */ public class BTServiceProfile implements Parcelable { public BluetoothGattService mService; public BTServiceProfile(BluetoothGattService service) { mService = service; } public BluetoothGattService getService() { return mService; } public static List<BluetoothGattService> getServiceList(List<BTServiceProfile> profileList) { List<BluetoothGattService> serviceList = new ArrayList<BluetoothGattService>(profileList.size()); for (BTServiceProfile profile : profileList) { serviceList.add(profile.getService()); } return serviceList; } public BTServiceProfile(Parcel in) {
// Path: DeviceService/src/com/ratio/util/UUIDUtils.java // public class UUIDUtils { // // // if the UUID is null, then we write 0L,0L // public static void writeToParcel(UUID uuid, Parcel parcel) { // if (uuid == null) { // parcel.writeLong(0L); // parcel.writeLong(0L); // } else { // parcel.writeLong(uuid.getLeastSignificantBits()); // parcel.writeLong(uuid.getMostSignificantBits()); // } // } // // // if the uuid is 0L,0L, then we assume that it is null // public static UUID readFromParcel(Parcel parcel) { // long lsb = parcel.readLong(); // long msb = parcel.readLong(); // if ((lsb == 0L) && (msb == 0L)) { // return null; // } else { // return new UUID(msb, lsb); // } // } // // // turn B6981800756211E2B50D00163E46F8FE into B6981800-7562-11E2-B50D-00163E46F8FE // public static UUID fromByteArray(byte[] byteArray, int offset) { // String format = "%s-%s-%s-%s-%s"; // String p1 = StringUtil.toHexCode(byteArray, offset + 0, 4); // String p2 = StringUtil.toHexCode(byteArray, offset + 4, 2); // String p3 = StringUtil.toHexCode(byteArray, offset + 6, 2); // String p4 = StringUtil.toHexCode(byteArray, offset + 8, 2); // String p5 = StringUtil.toHexCode(byteArray, offset + 10, 6); // String uuidString = String.format(format, p1, p2, p3, p4, p5); // return UUID.fromString(uuidString); // } // } // Path: DeviceService/src/com/ratio/deviceService/BTServiceProfile.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.ratio.util.UUIDUtils; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.os.Parcel; import android.os.Parcelable; package com.ratio.deviceService; /** * external description of a device profile, so once we query the device services and characteristics * we can send it back from the service to the activity in a bundle, which can be received by the BroadcastReceiver * @author mreynolds * */ public class BTServiceProfile implements Parcelable { public BluetoothGattService mService; public BTServiceProfile(BluetoothGattService service) { mService = service; } public BluetoothGattService getService() { return mService; } public static List<BluetoothGattService> getServiceList(List<BTServiceProfile> profileList) { List<BluetoothGattService> serviceList = new ArrayList<BluetoothGattService>(profileList.size()); for (BTServiceProfile profile : profileList) { serviceList.add(profile.getService()); } return serviceList; } public BTServiceProfile(Parcel in) {
UUID serviceUUID = UUIDUtils.readFromParcel(in);
RatioLabs/BLEService
DeviceService/src/com/ratio/deviceService/BTCharacteristicProfile.java
// Path: DeviceService/src/com/ratio/util/UUIDUtils.java // public class UUIDUtils { // // // if the UUID is null, then we write 0L,0L // public static void writeToParcel(UUID uuid, Parcel parcel) { // if (uuid == null) { // parcel.writeLong(0L); // parcel.writeLong(0L); // } else { // parcel.writeLong(uuid.getLeastSignificantBits()); // parcel.writeLong(uuid.getMostSignificantBits()); // } // } // // // if the uuid is 0L,0L, then we assume that it is null // public static UUID readFromParcel(Parcel parcel) { // long lsb = parcel.readLong(); // long msb = parcel.readLong(); // if ((lsb == 0L) && (msb == 0L)) { // return null; // } else { // return new UUID(msb, lsb); // } // } // // // turn B6981800756211E2B50D00163E46F8FE into B6981800-7562-11E2-B50D-00163E46F8FE // public static UUID fromByteArray(byte[] byteArray, int offset) { // String format = "%s-%s-%s-%s-%s"; // String p1 = StringUtil.toHexCode(byteArray, offset + 0, 4); // String p2 = StringUtil.toHexCode(byteArray, offset + 4, 2); // String p3 = StringUtil.toHexCode(byteArray, offset + 6, 2); // String p4 = StringUtil.toHexCode(byteArray, offset + 8, 2); // String p5 = StringUtil.toHexCode(byteArray, offset + 10, 6); // String uuidString = String.format(format, p1, p2, p3, p4, p5); // return UUID.fromString(uuidString); // } // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.ratio.util.UUIDUtils; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.os.Parcel; import android.os.Parcelable;
package com.ratio.deviceService; /** * external description of a device profile, so once we query the device services and characteristics * we can send it back from the service to the activity in a bundle, which can be received by the BroadcastReceiver * @author mreynolds * */ public class BTCharacteristicProfile implements Parcelable { protected BluetoothGattCharacteristic mCharacteristic; public BTCharacteristicProfile(BluetoothGattCharacteristic characteristic) { mCharacteristic = characteristic; } public BTCharacteristicProfile(UUID uuid, int properties, int permissions) { mCharacteristic = new BluetoothGattCharacteristic(uuid, properties, permissions); } public BluetoothGattCharacteristic getCharacteristic() { return mCharacteristic; } public static List<BluetoothGattCharacteristic> getCharacteristicList(List<BTCharacteristicProfile> characteristicProfileList) { ArrayList<BluetoothGattCharacteristic> charList = new ArrayList<BluetoothGattCharacteristic>(characteristicProfileList.size()); for (BTCharacteristicProfile profile : characteristicProfileList) { charList.add(profile.getCharacteristic()); } return charList; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) {
// Path: DeviceService/src/com/ratio/util/UUIDUtils.java // public class UUIDUtils { // // // if the UUID is null, then we write 0L,0L // public static void writeToParcel(UUID uuid, Parcel parcel) { // if (uuid == null) { // parcel.writeLong(0L); // parcel.writeLong(0L); // } else { // parcel.writeLong(uuid.getLeastSignificantBits()); // parcel.writeLong(uuid.getMostSignificantBits()); // } // } // // // if the uuid is 0L,0L, then we assume that it is null // public static UUID readFromParcel(Parcel parcel) { // long lsb = parcel.readLong(); // long msb = parcel.readLong(); // if ((lsb == 0L) && (msb == 0L)) { // return null; // } else { // return new UUID(msb, lsb); // } // } // // // turn B6981800756211E2B50D00163E46F8FE into B6981800-7562-11E2-B50D-00163E46F8FE // public static UUID fromByteArray(byte[] byteArray, int offset) { // String format = "%s-%s-%s-%s-%s"; // String p1 = StringUtil.toHexCode(byteArray, offset + 0, 4); // String p2 = StringUtil.toHexCode(byteArray, offset + 4, 2); // String p3 = StringUtil.toHexCode(byteArray, offset + 6, 2); // String p4 = StringUtil.toHexCode(byteArray, offset + 8, 2); // String p5 = StringUtil.toHexCode(byteArray, offset + 10, 6); // String uuidString = String.format(format, p1, p2, p3, p4, p5); // return UUID.fromString(uuidString); // } // } // Path: DeviceService/src/com/ratio/deviceService/BTCharacteristicProfile.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.ratio.util.UUIDUtils; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.os.Parcel; import android.os.Parcelable; package com.ratio.deviceService; /** * external description of a device profile, so once we query the device services and characteristics * we can send it back from the service to the activity in a bundle, which can be received by the BroadcastReceiver * @author mreynolds * */ public class BTCharacteristicProfile implements Parcelable { protected BluetoothGattCharacteristic mCharacteristic; public BTCharacteristicProfile(BluetoothGattCharacteristic characteristic) { mCharacteristic = characteristic; } public BTCharacteristicProfile(UUID uuid, int properties, int permissions) { mCharacteristic = new BluetoothGattCharacteristic(uuid, properties, permissions); } public BluetoothGattCharacteristic getCharacteristic() { return mCharacteristic; } public static List<BluetoothGattCharacteristic> getCharacteristicList(List<BTCharacteristicProfile> characteristicProfileList) { ArrayList<BluetoothGattCharacteristic> charList = new ArrayList<BluetoothGattCharacteristic>(characteristicProfileList.size()); for (BTCharacteristicProfile profile : characteristicProfileList) { charList.add(profile.getCharacteristic()); } return charList; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) {
UUIDUtils.writeToParcel(mCharacteristic.getUuid(), dest);
RatioLabs/BLEService
DeviceService/src/com/ratio/deviceService/DeviceService.java
// Path: DeviceService/src/com/ratio/exceptions/DeviceManagerException.java // public class DeviceManagerException extends Exception { // static final long serialVersionUID = 0; // // public DeviceManagerException(String s) { // super(s); // } // public DeviceManagerException(String error, String errorValue) { // super(String.format("%s %s", error, errorValue)); // } // } // // Path: DeviceService/src/com/ratio/exceptions/DeviceNameNotFoundException.java // public class DeviceNameNotFoundException extends Exception { // static final long serialVersionUID = 0; // // public DeviceNameNotFoundException(String s) { // super(s); // } // }
import java.util.ArrayList; import java.util.UUID; import com.ratio.exceptions.DeviceManagerException; import com.ratio.exceptions.DeviceNameNotFoundException; import com.ratio.deviceService.IDeviceCommand; import android.app.Service; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException;
public final static String EXTRA_VALUE = DeviceService.class.getName() + ".EXTRA_VALUE"; public final static String EXTRA_RSSI = DeviceService.class.getName() + ".EXTRA_RSSI"; public final static String EXTRA_STATUS = DeviceService.class.getName() + ".EXTRA_STATUS"; public final static String EXTRA_RETRIES_LEFT = DeviceService.class.getName() + ".EXTRA_RETRIES_LEFT"; protected static BTLEDeviceManager mDeviceManager; // device manager actually does device interface protected static int mPeriodMsec; // how many msec should we poll for? protected static UUID[] mAdvertisedServices; // advertised services to scan for protected static boolean mfInitialized = false; protected static boolean mfScanning = false; // scanning for BTLE devices, don't start another scan @Override public int onStartCommand(Intent intent, int flags, int startId) { if ((intent != null) && (intent.getAction() != null)) { // this is because we get the message from the broadcast receiver that toggles the bluetooth adapter. if (intent.getAction().equals(ACTION_PERFORM_SCAN)) { mfScanning = true; mDeviceManager.scanLeDevice(mAdvertisedServices, mPeriodMsec); } } return START_STICKY; } /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ public boolean initialize() { try { mDeviceManager = new BTLEDeviceManager(this, this);
// Path: DeviceService/src/com/ratio/exceptions/DeviceManagerException.java // public class DeviceManagerException extends Exception { // static final long serialVersionUID = 0; // // public DeviceManagerException(String s) { // super(s); // } // public DeviceManagerException(String error, String errorValue) { // super(String.format("%s %s", error, errorValue)); // } // } // // Path: DeviceService/src/com/ratio/exceptions/DeviceNameNotFoundException.java // public class DeviceNameNotFoundException extends Exception { // static final long serialVersionUID = 0; // // public DeviceNameNotFoundException(String s) { // super(s); // } // } // Path: DeviceService/src/com/ratio/deviceService/DeviceService.java import java.util.ArrayList; import java.util.UUID; import com.ratio.exceptions.DeviceManagerException; import com.ratio.exceptions.DeviceNameNotFoundException; import com.ratio.deviceService.IDeviceCommand; import android.app.Service; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; public final static String EXTRA_VALUE = DeviceService.class.getName() + ".EXTRA_VALUE"; public final static String EXTRA_RSSI = DeviceService.class.getName() + ".EXTRA_RSSI"; public final static String EXTRA_STATUS = DeviceService.class.getName() + ".EXTRA_STATUS"; public final static String EXTRA_RETRIES_LEFT = DeviceService.class.getName() + ".EXTRA_RETRIES_LEFT"; protected static BTLEDeviceManager mDeviceManager; // device manager actually does device interface protected static int mPeriodMsec; // how many msec should we poll for? protected static UUID[] mAdvertisedServices; // advertised services to scan for protected static boolean mfInitialized = false; protected static boolean mfScanning = false; // scanning for BTLE devices, don't start another scan @Override public int onStartCommand(Intent intent, int flags, int startId) { if ((intent != null) && (intent.getAction() != null)) { // this is because we get the message from the broadcast receiver that toggles the bluetooth adapter. if (intent.getAction().equals(ACTION_PERFORM_SCAN)) { mfScanning = true; mDeviceManager.scanLeDevice(mAdvertisedServices, mPeriodMsec); } } return START_STICKY; } /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ public boolean initialize() { try { mDeviceManager = new BTLEDeviceManager(this, this);
} catch (DeviceManagerException dmex) {
RatioLabs/BLEService
DeviceService/src/com/ratio/deviceService/DeviceService.java
// Path: DeviceService/src/com/ratio/exceptions/DeviceManagerException.java // public class DeviceManagerException extends Exception { // static final long serialVersionUID = 0; // // public DeviceManagerException(String s) { // super(s); // } // public DeviceManagerException(String error, String errorValue) { // super(String.format("%s %s", error, errorValue)); // } // } // // Path: DeviceService/src/com/ratio/exceptions/DeviceNameNotFoundException.java // public class DeviceNameNotFoundException extends Exception { // static final long serialVersionUID = 0; // // public DeviceNameNotFoundException(String s) { // super(s); // } // }
import java.util.ArrayList; import java.util.UUID; import com.ratio.exceptions.DeviceManagerException; import com.ratio.exceptions.DeviceNameNotFoundException; import com.ratio.deviceService.IDeviceCommand; import android.app.Service; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException;
Intent broadcastIntent = new Intent(ACTION_CONNECTION_STATE); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); broadcastIntent.putExtra(EXTRA_STATE, connState); sendBroadcast(broadcastIntent); } // report that we are attempting to reconnect to a device public void onRetryReconnect(BluetoothDevice device, int retriesLeft) { Intent broadcastIntent = new Intent(ACTION_RETRY_RECONNECT); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); broadcastIntent.putExtra(EXTRA_RETRIES_LEFT, retriesLeft); sendBroadcast(broadcastIntent); } // report that we have failed in our attempts to reconnect to a device public void onReconnectFailed(BluetoothDevice device) { Intent broadcastIntent = new Intent(ACTION_RECONNECT_FAILED); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); sendBroadcast(broadcastIntent); } // report that we have discovered the services published by a device. public void onServicesDiscovered(BluetoothDevice device, BluetoothGatt gatt) { try { BTDeviceProfile profile = mDeviceManager.getDeviceProfile(device.getAddress()); Intent broadcastIntent = new Intent(ACTION_SERVICES_DISCOVERED); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); broadcastIntent.putExtra(EXTRA_SERVICES, profile.mServiceProfileList); sendBroadcast(broadcastIntent);
// Path: DeviceService/src/com/ratio/exceptions/DeviceManagerException.java // public class DeviceManagerException extends Exception { // static final long serialVersionUID = 0; // // public DeviceManagerException(String s) { // super(s); // } // public DeviceManagerException(String error, String errorValue) { // super(String.format("%s %s", error, errorValue)); // } // } // // Path: DeviceService/src/com/ratio/exceptions/DeviceNameNotFoundException.java // public class DeviceNameNotFoundException extends Exception { // static final long serialVersionUID = 0; // // public DeviceNameNotFoundException(String s) { // super(s); // } // } // Path: DeviceService/src/com/ratio/deviceService/DeviceService.java import java.util.ArrayList; import java.util.UUID; import com.ratio.exceptions.DeviceManagerException; import com.ratio.exceptions.DeviceNameNotFoundException; import com.ratio.deviceService.IDeviceCommand; import android.app.Service; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; Intent broadcastIntent = new Intent(ACTION_CONNECTION_STATE); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); broadcastIntent.putExtra(EXTRA_STATE, connState); sendBroadcast(broadcastIntent); } // report that we are attempting to reconnect to a device public void onRetryReconnect(BluetoothDevice device, int retriesLeft) { Intent broadcastIntent = new Intent(ACTION_RETRY_RECONNECT); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); broadcastIntent.putExtra(EXTRA_RETRIES_LEFT, retriesLeft); sendBroadcast(broadcastIntent); } // report that we have failed in our attempts to reconnect to a device public void onReconnectFailed(BluetoothDevice device) { Intent broadcastIntent = new Intent(ACTION_RECONNECT_FAILED); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); sendBroadcast(broadcastIntent); } // report that we have discovered the services published by a device. public void onServicesDiscovered(BluetoothDevice device, BluetoothGatt gatt) { try { BTDeviceProfile profile = mDeviceManager.getDeviceProfile(device.getAddress()); Intent broadcastIntent = new Intent(ACTION_SERVICES_DISCOVERED); broadcastIntent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress()); broadcastIntent.putExtra(EXTRA_SERVICES, profile.mServiceProfileList); sendBroadcast(broadcastIntent);
} catch (DeviceNameNotFoundException dnnfex) {
RatioLabs/BLEService
DeviceService/src/com/ratio/deviceService/BTDescriptorProfile.java
// Path: DeviceService/src/com/ratio/util/UUIDUtils.java // public class UUIDUtils { // // // if the UUID is null, then we write 0L,0L // public static void writeToParcel(UUID uuid, Parcel parcel) { // if (uuid == null) { // parcel.writeLong(0L); // parcel.writeLong(0L); // } else { // parcel.writeLong(uuid.getLeastSignificantBits()); // parcel.writeLong(uuid.getMostSignificantBits()); // } // } // // // if the uuid is 0L,0L, then we assume that it is null // public static UUID readFromParcel(Parcel parcel) { // long lsb = parcel.readLong(); // long msb = parcel.readLong(); // if ((lsb == 0L) && (msb == 0L)) { // return null; // } else { // return new UUID(msb, lsb); // } // } // // // turn B6981800756211E2B50D00163E46F8FE into B6981800-7562-11E2-B50D-00163E46F8FE // public static UUID fromByteArray(byte[] byteArray, int offset) { // String format = "%s-%s-%s-%s-%s"; // String p1 = StringUtil.toHexCode(byteArray, offset + 0, 4); // String p2 = StringUtil.toHexCode(byteArray, offset + 4, 2); // String p3 = StringUtil.toHexCode(byteArray, offset + 6, 2); // String p4 = StringUtil.toHexCode(byteArray, offset + 8, 2); // String p5 = StringUtil.toHexCode(byteArray, offset + 10, 6); // String uuidString = String.format(format, p1, p2, p3, p4, p5); // return UUID.fromString(uuidString); // } // }
import java.util.UUID; import com.ratio.util.UUIDUtils; import android.bluetooth.BluetoothGattDescriptor; import android.os.Parcel; import android.os.Parcelable;
package com.ratio.deviceService; /** * external description of a device profile, so once we query the device services and descriptors * we can send it back from the service to the activity in a bundle, which can be received by the BroadcastReceiver * @author mreynolds * */ public class BTDescriptorProfile implements Parcelable { protected BluetoothGattDescriptor mDescriptor; public BTDescriptorProfile(BluetoothGattDescriptor descriptor) { mDescriptor = descriptor; } public BTDescriptorProfile(UUID uuid, int permissions) { mDescriptor = new BluetoothGattDescriptor(uuid, permissions); } public BluetoothGattDescriptor getDescriptor() { return mDescriptor; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) {
// Path: DeviceService/src/com/ratio/util/UUIDUtils.java // public class UUIDUtils { // // // if the UUID is null, then we write 0L,0L // public static void writeToParcel(UUID uuid, Parcel parcel) { // if (uuid == null) { // parcel.writeLong(0L); // parcel.writeLong(0L); // } else { // parcel.writeLong(uuid.getLeastSignificantBits()); // parcel.writeLong(uuid.getMostSignificantBits()); // } // } // // // if the uuid is 0L,0L, then we assume that it is null // public static UUID readFromParcel(Parcel parcel) { // long lsb = parcel.readLong(); // long msb = parcel.readLong(); // if ((lsb == 0L) && (msb == 0L)) { // return null; // } else { // return new UUID(msb, lsb); // } // } // // // turn B6981800756211E2B50D00163E46F8FE into B6981800-7562-11E2-B50D-00163E46F8FE // public static UUID fromByteArray(byte[] byteArray, int offset) { // String format = "%s-%s-%s-%s-%s"; // String p1 = StringUtil.toHexCode(byteArray, offset + 0, 4); // String p2 = StringUtil.toHexCode(byteArray, offset + 4, 2); // String p3 = StringUtil.toHexCode(byteArray, offset + 6, 2); // String p4 = StringUtil.toHexCode(byteArray, offset + 8, 2); // String p5 = StringUtil.toHexCode(byteArray, offset + 10, 6); // String uuidString = String.format(format, p1, p2, p3, p4, p5); // return UUID.fromString(uuidString); // } // } // Path: DeviceService/src/com/ratio/deviceService/BTDescriptorProfile.java import java.util.UUID; import com.ratio.util.UUIDUtils; import android.bluetooth.BluetoothGattDescriptor; import android.os.Parcel; import android.os.Parcelable; package com.ratio.deviceService; /** * external description of a device profile, so once we query the device services and descriptors * we can send it back from the service to the activity in a bundle, which can be received by the BroadcastReceiver * @author mreynolds * */ public class BTDescriptorProfile implements Parcelable { protected BluetoothGattDescriptor mDescriptor; public BTDescriptorProfile(BluetoothGattDescriptor descriptor) { mDescriptor = descriptor; } public BTDescriptorProfile(UUID uuid, int permissions) { mDescriptor = new BluetoothGattDescriptor(uuid, permissions); } public BluetoothGattDescriptor getDescriptor() { return mDescriptor; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) {
UUIDUtils.writeToParcel(mDescriptor.getUuid(), dest);
cornelcreanga/bitbucket-rest-client
src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/ErrorsParser.java
// Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/dto/BitBucketError.java // public class BitBucketError { // private String message; // private String context; // private String exceptionName; // // public BitBucketError(String message, String context, String exceptionName) { // this.context = context; // this.message = message; // this.exceptionName = exceptionName; // } // // @Nullable // public String getContext() { // return context; // } // // @Nullable // public String getMessage() { // return message; // } // // @Nullable // public String getExceptionName() { // return exceptionName; // } // // @Override // public String toString() { // return "BitBucketError{" + // "message='" + message + '\'' + // ", context='" + context + '\'' + // ", exceptionName='" + exceptionName + '\'' + // '}'; // } // } // // Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/Parsers.java // public static Function<JsonElement, BitBucketError> errorParser() { // return ERROR_PARSER; // } // // Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/Parsers.java // public static <T> Function<JsonElement, List<T>> listParser(Function<JsonElement, T> elementParser) { // return new ListParser<>(elementParser); // }
import com.ccreanga.bitbucket.rest.client.http.dto.BitBucketError; import java.util.function.Function; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.List; import static com.ccreanga.bitbucket.rest.client.http.responseparsers.Parsers.errorParser; import static com.ccreanga.bitbucket.rest.client.http.responseparsers.Parsers.listParser;
/* * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.ccreanga.bitbucket.rest.client.http.responseparsers; public class ErrorsParser implements Function<JsonElement, List<BitBucketError>> { @Override public List<BitBucketError> apply(JsonElement input) { JsonObject jsonObject = input.getAsJsonObject();
// Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/dto/BitBucketError.java // public class BitBucketError { // private String message; // private String context; // private String exceptionName; // // public BitBucketError(String message, String context, String exceptionName) { // this.context = context; // this.message = message; // this.exceptionName = exceptionName; // } // // @Nullable // public String getContext() { // return context; // } // // @Nullable // public String getMessage() { // return message; // } // // @Nullable // public String getExceptionName() { // return exceptionName; // } // // @Override // public String toString() { // return "BitBucketError{" + // "message='" + message + '\'' + // ", context='" + context + '\'' + // ", exceptionName='" + exceptionName + '\'' + // '}'; // } // } // // Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/Parsers.java // public static Function<JsonElement, BitBucketError> errorParser() { // return ERROR_PARSER; // } // // Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/Parsers.java // public static <T> Function<JsonElement, List<T>> listParser(Function<JsonElement, T> elementParser) { // return new ListParser<>(elementParser); // } // Path: src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/ErrorsParser.java import com.ccreanga.bitbucket.rest.client.http.dto.BitBucketError; import java.util.function.Function; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.List; import static com.ccreanga.bitbucket.rest.client.http.responseparsers.Parsers.errorParser; import static com.ccreanga.bitbucket.rest.client.http.responseparsers.Parsers.listParser; /* * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.ccreanga.bitbucket.rest.client.http.responseparsers; public class ErrorsParser implements Function<JsonElement, List<BitBucketError>> { @Override public List<BitBucketError> apply(JsonElement input) { JsonObject jsonObject = input.getAsJsonObject();
return listParser(errorParser()).apply(jsonObject.get("error"));