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
|
---|---|---|---|---|---|---|
kkung/kakao-android-sdk-standalone | sdk/src/com/kakao/SessionCallback.java | // Path: sdk/src/com/kakao/exception/KakaoException.java
// public class KakaoException extends RuntimeException {
// private static final long serialVersionUID = 3738785191273730776L;
// private ERROR_TYPE errorType;
//
// public enum ERROR_TYPE{
// ILLEGAL_ARGUMENT,
// MISS_CONFIGURATION,
// CANCELED_OPERATiON,
// AUTHORIZATION_FAILED,
// }
//
// public KakaoException(final ERROR_TYPE errorType, final String msg) {
// super(msg);
// this.errorType = errorType;
// }
//
// public boolean isCancledOperation() {
// return errorType == ERROR_TYPE.CANCELED_OPERATiON;
// }
//
// public KakaoException(final String msg) {
// super(msg);
// }
//
// public KakaoException(final Throwable t) {
// super(t);
// }
//
// public KakaoException(final String s, final Throwable t) {
// super(s, t);
// }
//
// public String getMessage(){
// if(errorType != null)
// return errorType.toString() +" : " + super.getMessage();
// else
// return super.getMessage();
// }
// }
| import com.kakao.exception.KakaoException; | /**
* Copyright 2014 Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* 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.kakao;
/**
* 세션의 상태 변경에 따른 콜백
* 세션이 오픈되었을 때, 세션이 만료되어 닫혔을 때 세션 콜백을 넘기게 된다.
*/
public interface SessionCallback {
/**
* access token을 성공적으로 발급 받아 valid access token을 가지고 있는 상태.
* 일반적으로 로그인 후의 다음 activity로 이동한다.
*/
public void onSessionOpened();
/**
* memory와 cache에 session 정보가 전혀 없는 상태.
* 일반적으로 로그인 버튼이 보이고 사용자가 클릭시 동의를 받아 access token 요청을 시도한다.
* @param exception close된 이유가 에러가 발생한 경우에 해당 exception.
*
*/ | // Path: sdk/src/com/kakao/exception/KakaoException.java
// public class KakaoException extends RuntimeException {
// private static final long serialVersionUID = 3738785191273730776L;
// private ERROR_TYPE errorType;
//
// public enum ERROR_TYPE{
// ILLEGAL_ARGUMENT,
// MISS_CONFIGURATION,
// CANCELED_OPERATiON,
// AUTHORIZATION_FAILED,
// }
//
// public KakaoException(final ERROR_TYPE errorType, final String msg) {
// super(msg);
// this.errorType = errorType;
// }
//
// public boolean isCancledOperation() {
// return errorType == ERROR_TYPE.CANCELED_OPERATiON;
// }
//
// public KakaoException(final String msg) {
// super(msg);
// }
//
// public KakaoException(final Throwable t) {
// super(t);
// }
//
// public KakaoException(final String s, final Throwable t) {
// super(s, t);
// }
//
// public String getMessage(){
// if(errorType != null)
// return errorType.toString() +" : " + super.getMessage();
// else
// return super.getMessage();
// }
// }
// Path: sdk/src/com/kakao/SessionCallback.java
import com.kakao.exception.KakaoException;
/**
* Copyright 2014 Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* 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.kakao;
/**
* 세션의 상태 변경에 따른 콜백
* 세션이 오픈되었을 때, 세션이 만료되어 닫혔을 때 세션 콜백을 넘기게 된다.
*/
public interface SessionCallback {
/**
* access token을 성공적으로 발급 받아 valid access token을 가지고 있는 상태.
* 일반적으로 로그인 후의 다음 activity로 이동한다.
*/
public void onSessionOpened();
/**
* memory와 cache에 session 정보가 전혀 없는 상태.
* 일반적으로 로그인 버튼이 보이고 사용자가 클릭시 동의를 받아 access token 요청을 시도한다.
* @param exception close된 이유가 에러가 발생한 경우에 해당 exception.
*
*/ | public void onSessionClosed(final KakaoException exception); |
kkung/kakao-android-sdk-standalone | sdk/src/com/kakao/helper/Utility.java | // Path: sdk/src/com/kakao/exception/KakaoException.java
// public class KakaoException extends RuntimeException {
// private static final long serialVersionUID = 3738785191273730776L;
// private ERROR_TYPE errorType;
//
// public enum ERROR_TYPE{
// ILLEGAL_ARGUMENT,
// MISS_CONFIGURATION,
// CANCELED_OPERATiON,
// AUTHORIZATION_FAILED,
// }
//
// public KakaoException(final ERROR_TYPE errorType, final String msg) {
// super(msg);
// this.errorType = errorType;
// }
//
// public boolean isCancledOperation() {
// return errorType == ERROR_TYPE.CANCELED_OPERATiON;
// }
//
// public KakaoException(final String msg) {
// super(msg);
// }
//
// public KakaoException(final Throwable t) {
// super(t);
// }
//
// public KakaoException(final String s, final Throwable t) {
// super(s, t);
// }
//
// public String getMessage(){
// if(errorType != null)
// return errorType.toString() +" : " + super.getMessage();
// else
// return super.getMessage();
// }
// }
| import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import com.kakao.exception.KakaoException; | public static Uri buildUri(final String authority, final String path) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(ServerProtocol.URL_SCHEME);
builder.authority(authority);
builder.path(path);
return builder.build();
}
public static Uri buildUri(final String authority, final String path, final Bundle parameters) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(ServerProtocol.URL_SCHEME);
builder.authority(authority);
builder.path(path);
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (parameter instanceof String) {
builder.appendQueryParameter(key, (String) parameter);
}
}
return builder.build();
}
public static void putObjectInBundle(final Bundle bundle, final String key, final Object value) {
if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof Parcelable) {
bundle.putParcelable(key, (Parcelable) value);
} else if (value instanceof byte[]) {
bundle.putByteArray(key, (byte[]) value);
} else { | // Path: sdk/src/com/kakao/exception/KakaoException.java
// public class KakaoException extends RuntimeException {
// private static final long serialVersionUID = 3738785191273730776L;
// private ERROR_TYPE errorType;
//
// public enum ERROR_TYPE{
// ILLEGAL_ARGUMENT,
// MISS_CONFIGURATION,
// CANCELED_OPERATiON,
// AUTHORIZATION_FAILED,
// }
//
// public KakaoException(final ERROR_TYPE errorType, final String msg) {
// super(msg);
// this.errorType = errorType;
// }
//
// public boolean isCancledOperation() {
// return errorType == ERROR_TYPE.CANCELED_OPERATiON;
// }
//
// public KakaoException(final String msg) {
// super(msg);
// }
//
// public KakaoException(final Throwable t) {
// super(t);
// }
//
// public KakaoException(final String s, final Throwable t) {
// super(s, t);
// }
//
// public String getMessage(){
// if(errorType != null)
// return errorType.toString() +" : " + super.getMessage();
// else
// return super.getMessage();
// }
// }
// Path: sdk/src/com/kakao/helper/Utility.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import com.kakao.exception.KakaoException;
public static Uri buildUri(final String authority, final String path) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(ServerProtocol.URL_SCHEME);
builder.authority(authority);
builder.path(path);
return builder.build();
}
public static Uri buildUri(final String authority, final String path, final Bundle parameters) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(ServerProtocol.URL_SCHEME);
builder.authority(authority);
builder.path(path);
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (parameter instanceof String) {
builder.appendQueryParameter(key, (String) parameter);
}
}
return builder.build();
}
public static void putObjectInBundle(final Bundle bundle, final String key, final Object value) {
if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof Parcelable) {
bundle.putParcelable(key, (Parcelable) value);
} else if (value instanceof byte[]) {
bundle.putByteArray(key, (byte[]) value);
} else { | throw new KakaoException("attempted to add unsupported type to Bundle"); |
kkung/kakao-android-sdk-standalone | sdk/src/com/kakao/internal/ActionInfo.java | // Path: sdk/src/com/kakao/AppActionBuilder.java
// public enum DEVICE_TYPE {
// /**
// * 핸드폰
// */
// PHONE("phone"),
// /**
// * 패드
// */
// PAD("pad");
//
// private final String value;
//
// DEVICE_TYPE(String value) {
// this.value = value;
// }
//
// /**
// * 디바이스 종류의 string 값
// * 메시지를 json으로 만들때 사용된다.
// * @return 디바이스 종류의 string 값. 메시지를 json으로 만들때 사용된다.
// */
// public String getValue() {
// return value;
// }
// }
| import org.json.JSONObject;
import android.text.TextUtils;
import com.kakao.AppActionBuilder.DEVICE_TYPE;
import org.json.JSONException; | /**
* Copyright 2014 Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* 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.kakao.internal;
public class ActionInfo {
enum ACTION_INFO_OS {
ANDROID("android"),
IOS("ios");
private final String value;
ACTION_INFO_OS(String value) {
this.value = value;
}
}
private final ACTION_INFO_OS os; | // Path: sdk/src/com/kakao/AppActionBuilder.java
// public enum DEVICE_TYPE {
// /**
// * 핸드폰
// */
// PHONE("phone"),
// /**
// * 패드
// */
// PAD("pad");
//
// private final String value;
//
// DEVICE_TYPE(String value) {
// this.value = value;
// }
//
// /**
// * 디바이스 종류의 string 값
// * 메시지를 json으로 만들때 사용된다.
// * @return 디바이스 종류의 string 값. 메시지를 json으로 만들때 사용된다.
// */
// public String getValue() {
// return value;
// }
// }
// Path: sdk/src/com/kakao/internal/ActionInfo.java
import org.json.JSONObject;
import android.text.TextUtils;
import com.kakao.AppActionBuilder.DEVICE_TYPE;
import org.json.JSONException;
/**
* Copyright 2014 Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* 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.kakao.internal;
public class ActionInfo {
enum ACTION_INFO_OS {
ANDROID("android"),
IOS("ios");
private final String value;
ACTION_INFO_OS(String value) {
this.value = value;
}
}
private final ACTION_INFO_OS os; | private final DEVICE_TYPE deviceType; |
alechenninger/monarch | bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java | // Path: lib/src/io/github/alechenninger/monarch/SourceSpec.java
// public interface SourceSpec {
//
// Change toChange(Map<String, Object> set, Collection<String> remove);
//
// Optional<Source> findSource(Hierarchy hierarchy);
//
// Object toStringOrMap();
//
// @SuppressWarnings("unchecked")
// static List<SourceSpec> fromStringOrMap(Object object) {
// if (object instanceof String) {
// return BraceExpand.string((String) object).stream()
// .map(SourceSpec::byPath)
// .collect(Collectors.toList());
// }
//
// if (object instanceof Map) {
// return BraceExpand.keysAndValuesOf((Map<String, String>) object).stream()
// .map(SourceSpec::byVariables)
// .collect(Collectors.toList());
// }
//
// throw new IllegalArgumentException("Expected String or Map but got: " + object);
// }
//
// /**
// * @param expressions One or more "key=value" expressions or a single path.
// */
// static SourceSpec fromExpressions(List<String> expressions) {
// if (expressions.isEmpty()) {
// throw new IllegalArgumentException("Cannot parse a SourceSpec from an empty expressions " +
// "list. Provide at least one expression.");
// }
//
// if (expressions.size() == 1) {
// String expression = expressions.get(0);
//
// String[] keyValue = expression.split("=", 2);
// if (keyValue.length == 2) {
// return byVariables(Collections.singletonMap(keyValue[0], keyValue[1]));
// }
//
// return byPath(expression);
// }
//
// Map<String, String> variables = expressions.stream()
// .map(expression -> {
// String[] keyValue = expression.split("=", 2);
//
// if (keyValue.length != 2) {
// throw new IllegalArgumentException("Multiple source spec expressions provided but " +
// "one of them was not a key=value pair. Cannot parse '" + expression + "' in " +
// expressions);
// }
//
// return keyValue;
// })
// .collect(Collectors.toMap(kv -> kv[0], kv -> kv[1]));
//
// return byVariables(variables);
// }
//
// static SourceSpec byVariables(Map<String, String> variables) {
// return new VariableSourceSpec(variables);
// }
//
// static SourceSpec byPath(String path) {
// return new PathSourceSpec(path);
// }
//
// class VariableSourceSpec implements SourceSpec {
// private final Map<String, String> variables;
//
// VariableSourceSpec(Map<String, String> variables) {
// this.variables = Collections.unmodifiableMap(new HashMap<>(variables));
// }
//
// @Override
// public Change toChange(Map<String, Object> set, Collection<String> remove) {
// return Change.forVariables(variables, set, remove);
// }
//
// @Override
// public Optional<Source> findSource(Hierarchy hierarchy) {
// return hierarchy.sourceFor(variables);
// }
//
// @Override
// public Object toStringOrMap() {
// return variables;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// VariableSourceSpec that = (VariableSourceSpec) o;
// return Objects.equals(variables, that.variables);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(variables);
// }
//
// @Override
// public String toString() {
// return "VariableSourceSpec{" +
// "variables=" + variables +
// '}';
// }
// }
//
// class PathSourceSpec implements SourceSpec {
// private final String path;
//
// PathSourceSpec(String path) {
// this.path = path;
// }
//
// @Override
// public Change toChange(Map<String, Object> set, Collection<String> remove) {
// return Change.forPath(path, set, remove);
// }
//
// @Override
// public Optional<Source> findSource(Hierarchy hierarchy) {
// return hierarchy.sourceFor(path);
// }
//
// @Override
// public Object toStringOrMap() {
// return path;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// PathSourceSpec that = (PathSourceSpec) o;
// return Objects.equals(path, that.path);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path);
// }
//
// @Override
// public String toString() {
// return "PathSourceSpec{" +
// "path='" + path + '\'' +
// '}';
// }
// }
// }
| import io.github.alechenninger.monarch.SourceSpec;
import java.util.List;
import java.util.Optional; | /*
* monarch - A tool for managing hierarchical data.
* Copyright (C) 2016 Alec Henninger
*
* 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 io.github.alechenninger.monarch.set;
public interface UpdateSetInput {
/**
* Path of changes to read from and update (or create, if the path does not exist).
*/
Optional<String> getChangesPath();
/**
* Source for the change we wish to modify or create.
*/ | // Path: lib/src/io/github/alechenninger/monarch/SourceSpec.java
// public interface SourceSpec {
//
// Change toChange(Map<String, Object> set, Collection<String> remove);
//
// Optional<Source> findSource(Hierarchy hierarchy);
//
// Object toStringOrMap();
//
// @SuppressWarnings("unchecked")
// static List<SourceSpec> fromStringOrMap(Object object) {
// if (object instanceof String) {
// return BraceExpand.string((String) object).stream()
// .map(SourceSpec::byPath)
// .collect(Collectors.toList());
// }
//
// if (object instanceof Map) {
// return BraceExpand.keysAndValuesOf((Map<String, String>) object).stream()
// .map(SourceSpec::byVariables)
// .collect(Collectors.toList());
// }
//
// throw new IllegalArgumentException("Expected String or Map but got: " + object);
// }
//
// /**
// * @param expressions One or more "key=value" expressions or a single path.
// */
// static SourceSpec fromExpressions(List<String> expressions) {
// if (expressions.isEmpty()) {
// throw new IllegalArgumentException("Cannot parse a SourceSpec from an empty expressions " +
// "list. Provide at least one expression.");
// }
//
// if (expressions.size() == 1) {
// String expression = expressions.get(0);
//
// String[] keyValue = expression.split("=", 2);
// if (keyValue.length == 2) {
// return byVariables(Collections.singletonMap(keyValue[0], keyValue[1]));
// }
//
// return byPath(expression);
// }
//
// Map<String, String> variables = expressions.stream()
// .map(expression -> {
// String[] keyValue = expression.split("=", 2);
//
// if (keyValue.length != 2) {
// throw new IllegalArgumentException("Multiple source spec expressions provided but " +
// "one of them was not a key=value pair. Cannot parse '" + expression + "' in " +
// expressions);
// }
//
// return keyValue;
// })
// .collect(Collectors.toMap(kv -> kv[0], kv -> kv[1]));
//
// return byVariables(variables);
// }
//
// static SourceSpec byVariables(Map<String, String> variables) {
// return new VariableSourceSpec(variables);
// }
//
// static SourceSpec byPath(String path) {
// return new PathSourceSpec(path);
// }
//
// class VariableSourceSpec implements SourceSpec {
// private final Map<String, String> variables;
//
// VariableSourceSpec(Map<String, String> variables) {
// this.variables = Collections.unmodifiableMap(new HashMap<>(variables));
// }
//
// @Override
// public Change toChange(Map<String, Object> set, Collection<String> remove) {
// return Change.forVariables(variables, set, remove);
// }
//
// @Override
// public Optional<Source> findSource(Hierarchy hierarchy) {
// return hierarchy.sourceFor(variables);
// }
//
// @Override
// public Object toStringOrMap() {
// return variables;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// VariableSourceSpec that = (VariableSourceSpec) o;
// return Objects.equals(variables, that.variables);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(variables);
// }
//
// @Override
// public String toString() {
// return "VariableSourceSpec{" +
// "variables=" + variables +
// '}';
// }
// }
//
// class PathSourceSpec implements SourceSpec {
// private final String path;
//
// PathSourceSpec(String path) {
// this.path = path;
// }
//
// @Override
// public Change toChange(Map<String, Object> set, Collection<String> remove) {
// return Change.forPath(path, set, remove);
// }
//
// @Override
// public Optional<Source> findSource(Hierarchy hierarchy) {
// return hierarchy.sourceFor(path);
// }
//
// @Override
// public Object toStringOrMap() {
// return path;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// PathSourceSpec that = (PathSourceSpec) o;
// return Objects.equals(path, that.path);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path);
// }
//
// @Override
// public String toString() {
// return "PathSourceSpec{" +
// "path='" + path + '\'' +
// '}';
// }
// }
// }
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
import io.github.alechenninger.monarch.SourceSpec;
import java.util.List;
import java.util.Optional;
/*
* monarch - A tool for managing hierarchical data.
* Copyright (C) 2016 Alec Henninger
*
* 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 io.github.alechenninger.monarch.set;
public interface UpdateSetInput {
/**
* Path of changes to read from and update (or create, if the path does not exist).
*/
Optional<String> getChangesPath();
/**
* Source for the change we wish to modify or create.
*/ | Optional<SourceSpec> getSource(); |
alechenninger/monarch | lib/src/io/github/alechenninger/monarch/DynamicHierarchy.java | // Path: lib/src/io/github/alechenninger/monarch/DynamicNode.java
// final class RenderedNode {
// private final DynamicNode node;
// private final String path;
// private final Set<Assignment> usedAssignments;
// private final int hash;
//
// public RenderedNode(String path, Set<Assignment> usedAssignments, DynamicNode node) {
// this.path = Objects.requireNonNull(path, "path");
// this.usedAssignments = Objects.requireNonNull(usedAssignments, "usedAssignments");
// this.node = Objects.requireNonNull(node, "node");
//
// hash = Objects.hash(node, path, usedAssignments);
// }
//
// public String path() {
// return path;
// }
//
// public Set<Assignment> usedAssignments() {
// return usedAssignments;
// }
//
// public DynamicNode node() {
// return node;
// }
//
// @Override
// public String toString() {
// return "RenderedNode{" +
// "node=" + node +
// ", path='" + path + '\'' +
// ", usedAssignments=" + usedAssignments +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// RenderedNode that = (RenderedNode) o;
// return Objects.equals(node, that.node) &&
// Objects.equals(path, that.path) &&
// Objects.equals(usedAssignments, that.usedAssignments);
// }
//
// @Override
// public int hashCode() {
// return hash;
// }
// }
| import io.github.alechenninger.monarch.DynamicNode.RenderedNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream; | // TODO: error
break;
}
}
}
if (target == null) {
cachedSources.put(assignments, null);
return Optional.empty();
}
cachedSources.put(assignments, target);
return Optional.of(target);
}
@Override
public List<Source> allSources() {
if (cachedAll != null) {
return cachedAll;
}
if (nodes.isEmpty()) {
return cachedAll = Collections.emptyList();
}
List<Source> descendants = new ArrayList<>();
for (int i = 0; i < nodes.size(); i++) {
DynamicNode dynamicNode = nodes.get(i);
| // Path: lib/src/io/github/alechenninger/monarch/DynamicNode.java
// final class RenderedNode {
// private final DynamicNode node;
// private final String path;
// private final Set<Assignment> usedAssignments;
// private final int hash;
//
// public RenderedNode(String path, Set<Assignment> usedAssignments, DynamicNode node) {
// this.path = Objects.requireNonNull(path, "path");
// this.usedAssignments = Objects.requireNonNull(usedAssignments, "usedAssignments");
// this.node = Objects.requireNonNull(node, "node");
//
// hash = Objects.hash(node, path, usedAssignments);
// }
//
// public String path() {
// return path;
// }
//
// public Set<Assignment> usedAssignments() {
// return usedAssignments;
// }
//
// public DynamicNode node() {
// return node;
// }
//
// @Override
// public String toString() {
// return "RenderedNode{" +
// "node=" + node +
// ", path='" + path + '\'' +
// ", usedAssignments=" + usedAssignments +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// RenderedNode that = (RenderedNode) o;
// return Objects.equals(node, that.node) &&
// Objects.equals(path, that.path) &&
// Objects.equals(usedAssignments, that.usedAssignments);
// }
//
// @Override
// public int hashCode() {
// return hash;
// }
// }
// Path: lib/src/io/github/alechenninger/monarch/DynamicHierarchy.java
import io.github.alechenninger.monarch.DynamicNode.RenderedNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
// TODO: error
break;
}
}
}
if (target == null) {
cachedSources.put(assignments, null);
return Optional.empty();
}
cachedSources.put(assignments, target);
return Optional.of(target);
}
@Override
public List<Source> allSources() {
if (cachedAll != null) {
return cachedAll;
}
if (nodes.isEmpty()) {
return cachedAll = Collections.emptyList();
}
List<Source> descendants = new ArrayList<>();
for (int i = 0; i < nodes.size(); i++) {
DynamicNode dynamicNode = nodes.get(i);
| for (RenderedNode rendered : dynamicNode.render(Assignments.none(inventory))) { |
alechenninger/monarch | bin/src/io/github/alechenninger/monarch/CommandInput.java | // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
| import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level; | /*
* monarch - A tool for managing hierarchical data.
* Copyright (C) 2016 Alec Henninger
*
* 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 io.github.alechenninger.monarch;
public interface CommandInput {
List<ApplyChangesInput> getApplyCommands();
| // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
// Path: bin/src/io/github/alechenninger/monarch/CommandInput.java
import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
/*
* monarch - A tool for managing hierarchical data.
* Copyright (C) 2016 Alec Henninger
*
* 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 io.github.alechenninger.monarch;
public interface CommandInput {
List<ApplyChangesInput> getApplyCommands();
| List<UpdateSetInput> getUpdateSetCommands(); |
alechenninger/monarch | bin/src/io/github/alechenninger/monarch/SerializableConfig.java | // Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
| import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import java.util.Set; |
public Yaml getYaml() {
return yaml;
}
public void setYaml(Yaml yaml) {
this.yaml = yaml;
}
}
public static class Yaml {
private Integer indent;
private Isolate isolate;
public Integer getIndent() {
return indent;
}
public void setIndent(Integer indent) {
this.indent = indent;
}
public Isolate getIsolate() {
return isolate;
}
public void setIsolate(Isolate isolate) {
this.isolate = isolate;
}
| // Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
// Path: bin/src/io/github/alechenninger/monarch/SerializableConfig.java
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import java.util.Set;
public Yaml getYaml() {
return yaml;
}
public void setYaml(Yaml yaml) {
this.yaml = yaml;
}
}
public static class Yaml {
private Integer indent;
private Isolate isolate;
public Integer getIndent() {
return indent;
}
public void setIndent(Integer indent) {
this.indent = indent;
}
public Isolate getIsolate() {
return isolate;
}
public void setIsolate(Isolate isolate) {
this.isolate = isolate;
}
| public YamlConfiguration toYamlConfiguration() { |
alechenninger/monarch | bin/src/io/github/alechenninger/monarch/ArgParseMonarchArgParser.java | // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
//
// Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
| import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.impl.action.StoreTrueArgumentAction;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.internal.UnrecognizedArgumentException;
import net.sourceforge.argparse4j.internal.UnrecognizedCommandException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors; | parser.addArgument("-?", "--help")
.dest("help")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show this message and exit.");
parser.addArgument("-v", "--version")
.dest("show_version")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show the running version of monarch and exit.");
MutuallyExclusiveGroup logGroup = parser.addMutuallyExclusiveGroup("logging flags")
.description("Control log levels. Without either flag, some logs are written. " +
"Errors and warnings are output to stderr.");
logGroup.addArgument("--verbose")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("verbose")
.help("Log everything. Useful to understand what your changeset is doing.");
logGroup.addArgument("--quiet")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("quiet")
.help("Log nothing.");
Subparsers subparsers = parser.addSubparsers().dest(SUBPARSER_DEST)
.title("commands")
.help("Pass --help to a command for more information.");
| // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
//
// Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
// Path: bin/src/io/github/alechenninger/monarch/ArgParseMonarchArgParser.java
import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.impl.action.StoreTrueArgumentAction;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.internal.UnrecognizedArgumentException;
import net.sourceforge.argparse4j.internal.UnrecognizedCommandException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
parser.addArgument("-?", "--help")
.dest("help")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show this message and exit.");
parser.addArgument("-v", "--version")
.dest("show_version")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show the running version of monarch and exit.");
MutuallyExclusiveGroup logGroup = parser.addMutuallyExclusiveGroup("logging flags")
.description("Control log levels. Without either flag, some logs are written. " +
"Errors and warnings are output to stderr.");
logGroup.addArgument("--verbose")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("verbose")
.help("Log everything. Useful to understand what your changeset is doing.");
logGroup.addArgument("--quiet")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("quiet")
.help("Log nothing.");
Subparsers subparsers = parser.addSubparsers().dest(SUBPARSER_DEST)
.title("commands")
.help("Pass --help to a command for more information.");
| InputFactory<ApplyChangesInput> applyChangesFactory = applySpec.addToSubparsers(subparsers); |
alechenninger/monarch | bin/src/io/github/alechenninger/monarch/ArgParseMonarchArgParser.java | // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
//
// Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
| import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.impl.action.StoreTrueArgumentAction;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.internal.UnrecognizedArgumentException;
import net.sourceforge.argparse4j.internal.UnrecognizedCommandException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors; | .dest("help")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show this message and exit.");
parser.addArgument("-v", "--version")
.dest("show_version")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show the running version of monarch and exit.");
MutuallyExclusiveGroup logGroup = parser.addMutuallyExclusiveGroup("logging flags")
.description("Control log levels. Without either flag, some logs are written. " +
"Errors and warnings are output to stderr.");
logGroup.addArgument("--verbose")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("verbose")
.help("Log everything. Useful to understand what your changeset is doing.");
logGroup.addArgument("--quiet")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("quiet")
.help("Log nothing.");
Subparsers subparsers = parser.addSubparsers().dest(SUBPARSER_DEST)
.title("commands")
.help("Pass --help to a command for more information.");
InputFactory<ApplyChangesInput> applyChangesFactory = applySpec.addToSubparsers(subparsers); | // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
//
// Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
// Path: bin/src/io/github/alechenninger/monarch/ArgParseMonarchArgParser.java
import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.impl.action.StoreTrueArgumentAction;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.internal.UnrecognizedArgumentException;
import net.sourceforge.argparse4j.internal.UnrecognizedCommandException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
.dest("help")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show this message and exit.");
parser.addArgument("-v", "--version")
.dest("show_version")
.action(new AbortParsingAction(Arguments.storeTrue()))
.help("Show the running version of monarch and exit.");
MutuallyExclusiveGroup logGroup = parser.addMutuallyExclusiveGroup("logging flags")
.description("Control log levels. Without either flag, some logs are written. " +
"Errors and warnings are output to stderr.");
logGroup.addArgument("--verbose")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("verbose")
.help("Log everything. Useful to understand what your changeset is doing.");
logGroup.addArgument("--quiet")
.action(new StoreTrueArgumentAction())
.setDefault(false)
.dest("quiet")
.help("Log nothing.");
Subparsers subparsers = parser.addSubparsers().dest(SUBPARSER_DEST)
.title("commands")
.help("Pass --help to a command for more information.");
InputFactory<ApplyChangesInput> applyChangesFactory = applySpec.addToSubparsers(subparsers); | InputFactory<UpdateSetInput> updateSetFactory = updateSetSpec.addToSubparsers(subparsers); |
alechenninger/monarch | bin/src/io/github/alechenninger/monarch/ArgParseMonarchArgParser.java | // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
//
// Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
| import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.impl.action.StoreTrueArgumentAction;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.internal.UnrecognizedArgumentException;
import net.sourceforge.argparse4j.internal.UnrecognizedCommandException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors; | "When a variable is assigned a value, its implicit assignments are applied " +
"simultaneously. Assignments may rule out possible values for a variable if those " +
"values would imply conflicts with known assignments."
);
subparser.addArgument("--data-dir", "-d")
.dest("data_dir")
.help("Path to where existing data sources life. The data for sources describe in the "
+ "hierarchy is looked using the paths in the hierarchy relative to this folder. "
+ "If not provided, will look for a value in config files with key 'dataDir'.");
subparser.addArgument("--output-dir", "-o")
.dest("output_dir")
.help("Path to directory where result data sources will be written. Data sources will be "
+ "written using relative paths from hierarchy. If not provided, will look for a "
+ "value in config files with key 'outputDir'.");
subparser.addArgument("--merge-keys", "-m")
.dest("merge_keys")
.metavar("MERGE_KEY")
.nargs("+")
.help("Space-delimited list of keys which should be inherited with merge semantics. "
+ "That is, normally the value that is inherited for a given key is only the nearest "
+ "ancestor's value. Keys that are in the merge key list however inherit values from "
+ "all of their ancestor's and merge them together, provided they are like types of "
+ "either collections or maps. If not provided, will look for an array value in "
+ "config files with key 'outputDir'.");
subparser.addArgument("--yaml-isolate")
.dest("yaml_isolate") | // Path: bin/src/io/github/alechenninger/monarch/apply/ApplyChangesInput.java
// public interface ApplyChangesInput {
// Optional<String> getHierarchyPathOrYaml();
//
// Optional<String> getChangesPathOrYaml();
//
// Optional<SourceSpec> getTarget();
//
// Optional<String> getDataDir();
//
// List<String> getConfigPaths();
//
// Optional<String> getOutputDir();
//
// List<String> getMergeKeys();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
//
// Optional<YamlConfiguration.Isolate> getYamlIsolate();
//
// }
//
// Path: bin/src/io/github/alechenninger/monarch/set/UpdateSetInput.java
// public interface UpdateSetInput {
// /**
// * Path of changes to read from and update (or create, if the path does not exist).
// */
// Optional<String> getChangesPath();
//
// /**
// * Source for the change we wish to modify or create.
// */
// Optional<SourceSpec> getSource();
//
// /**
// * A list of key value pairs to add or replace in the set block of the source's change.
// *
// * <p>The list may contain paths to yaml files or inline yaml heterogeneously.
// */
// List<String> getPutPathsOrYaml();
//
// /**
// * A list of keys to remove from the set block of the source's change.
// */
// List<String> getRemovals();
//
// Optional<String> getHierarchyPathOrYaml();
//
// List<String> getConfigPaths();
//
// boolean isHelpRequested();
//
// String getHelpMessage();
// }
//
// Path: bin/src/io/github/alechenninger/monarch/yaml/YamlConfiguration.java
// public interface YamlConfiguration {
// YamlConfiguration DEFAULT = new Default();
//
// default int indent() {
// return 2;
// }
//
// default Isolate updateIsolation() {
// return Isolate.ALWAYS;
// }
//
// enum Isolate {
// ALWAYS,
// // TODO: Support WHEN_POSSIBLE
// // This involves modifying unmanaged portion while maintaining formatting and whitespace.
// // Not trivial to do.
// //WHEN_POSSIBLE,
// NEVER;
// }
//
// /** Extendable for reusable toString */
// class Default implements YamlConfiguration {
// @Override
// public String toString() {
// return "YamlConfiguration{" +
// "indent=" + indent() +
// ", updateIsolation=" + updateIsolation() +
// '}';
// }
// }
// }
// Path: bin/src/io/github/alechenninger/monarch/ArgParseMonarchArgParser.java
import io.github.alechenninger.monarch.apply.ApplyChangesInput;
import io.github.alechenninger.monarch.set.UpdateSetInput;
import io.github.alechenninger.monarch.yaml.YamlConfiguration;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.impl.action.StoreTrueArgumentAction;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import net.sourceforge.argparse4j.internal.UnrecognizedArgumentException;
import net.sourceforge.argparse4j.internal.UnrecognizedCommandException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
"When a variable is assigned a value, its implicit assignments are applied " +
"simultaneously. Assignments may rule out possible values for a variable if those " +
"values would imply conflicts with known assignments."
);
subparser.addArgument("--data-dir", "-d")
.dest("data_dir")
.help("Path to where existing data sources life. The data for sources describe in the "
+ "hierarchy is looked using the paths in the hierarchy relative to this folder. "
+ "If not provided, will look for a value in config files with key 'dataDir'.");
subparser.addArgument("--output-dir", "-o")
.dest("output_dir")
.help("Path to directory where result data sources will be written. Data sources will be "
+ "written using relative paths from hierarchy. If not provided, will look for a "
+ "value in config files with key 'outputDir'.");
subparser.addArgument("--merge-keys", "-m")
.dest("merge_keys")
.metavar("MERGE_KEY")
.nargs("+")
.help("Space-delimited list of keys which should be inherited with merge semantics. "
+ "That is, normally the value that is inherited for a given key is only the nearest "
+ "ancestor's value. Keys that are in the merge key list however inherit values from "
+ "all of their ancestor's and merge them together, provided they are like types of "
+ "either collections or maps. If not provided, will look for an array value in "
+ "config files with key 'outputDir'.");
subparser.addArgument("--yaml-isolate")
.dest("yaml_isolate") | .choices(Arrays.stream(YamlConfiguration.Isolate.values()) |
headwirecom/aemdc | src/main/java/com/headwire/aemdc/companion/RunnableCompanion.java | // Path: src/main/java/com/headwire/aemdc/runner/BasisRunner.java
// public abstract class BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(BasisRunner.class);
//
// protected Resource resource;
//
// /**
// * Invoker invokes commands here
// *
// * @throws IOException
// */
// public abstract void run() throws IOException;
//
// /**
// * Get help folder name for template type.
// * Help folders files are under /resources/types/<type>/help/..
// * or /aemdc-files/<type>/help/..
// *
// * @return help folder path
// */
// public abstract String getHelpFolder();
//
// /**
// * Get help folder name for template name.
// * Help folders files are under /aemdc-files/<type>/<template name>/help/..
// *
// * @return help folder path
// */
// public abstract String getTemplateHelpFolder();
//
// /**
// * Get template type source folder path.
// *
// * @return
// */
// public abstract String getSourceFolder();
//
// /**
// * Get place holder replacer.
// *
// * @return place holder replacer
// */
// public abstract Replacer getPlaceHolderReplacer();
//
// /**
// * Get resource
// *
// * @return resource
// */
// public Resource getResource() {
// return resource;
// }
//
// /**
// * Set global config properties in the resource
// *
// * @param config
// * - properties config
// */
// public void setGlobalConfigProperties(final Config config) {
// // Set extensions from config file
// final String[] extensions = config.getFileExtensions();
// getResource().setExtensions(extensions);
//
// // Set overwriting methods from config file
// if (Constants.EXISTING_DESTINATION_RESOURCES_WARN
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToWarnDestDir(true);
// } else if (Constants.EXISTING_DESTINATION_RESOURCES_DELETE
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToDeleteDestDir(true);
// }
// }
// }
//
// Path: src/main/java/com/headwire/aemdc/runner/HelpRunner.java
// public class HelpRunner extends BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(HelpRunner.class);
// private static final String HELP_FOLDER = "help";
//
// /**
// * Invoker
// */
// private final CommandMenu menu = new CommandMenu();
// private final Config config;
//
// /**
// * Constructor
// *
// * @param resource
// * - resource object
// */
// public HelpRunner(final Resource resource, final Config config) {
// this.resource = resource;
// this.config = config;
//
// LOG.debug("Help runner starting...");
//
// // Creates Invoker object, command object and configure them
// menu.setCommand(1, new HelpCommand(resource, config));
// }
//
// /**
// * Run commands
// *
// * @throws IOException
// */
// @Override
// public void run() throws IOException {
// // Invoker invokes command
// menu.runCommand(1);
// }
//
// @Override
// public String getHelpFolder() {
// return Constants.TYPES_STATIC_FOLDER + "/" + HELP_FOLDER;
// }
//
// @Override
// public String getTemplateHelpFolder() {
// return getHelpFolder();
// }
//
// @Override
// public String getSourceFolder() {
// return resource.getSourceFolderPath();
// }
//
// @Override
// public Replacer getPlaceHolderReplacer() {
// return null;
// }
// }
| import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.headwire.aemdc.runner.BasisRunner;
import com.headwire.aemdc.runner.HelpRunner;
import ch.qos.logback.classic.Level; | package com.headwire.aemdc.companion;
/**
* Runnable Companion Main Class
*
* @author Marat Saitov, 25.10.2016
*/
public class RunnableCompanion {
private static final Logger LOG = LoggerFactory.getLogger(RunnableCompanion.class);
private static final ch.qos.logback.classic.Logger ROOT_LOGGER = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
private static Config config;
/**
* Main start method.
*
* @param args
* - arguments
* @throws IOException
* - IOException
*/
public static void main(final String[] args) throws IOException {
// set default INFO log level to avoid logging from ConfigUtil
ROOT_LOGGER.setLevel(Level.INFO);
// Get Properties Config from config file
config = new Config(args);
// setup custom log level
if (setupCustomLogLevel()) {
// Check configuration from configuration properties file
config.checkConfiguration();
}
// set mandatories from arguments
final Resource resource = new Resource(args);
// Get Runner | // Path: src/main/java/com/headwire/aemdc/runner/BasisRunner.java
// public abstract class BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(BasisRunner.class);
//
// protected Resource resource;
//
// /**
// * Invoker invokes commands here
// *
// * @throws IOException
// */
// public abstract void run() throws IOException;
//
// /**
// * Get help folder name for template type.
// * Help folders files are under /resources/types/<type>/help/..
// * or /aemdc-files/<type>/help/..
// *
// * @return help folder path
// */
// public abstract String getHelpFolder();
//
// /**
// * Get help folder name for template name.
// * Help folders files are under /aemdc-files/<type>/<template name>/help/..
// *
// * @return help folder path
// */
// public abstract String getTemplateHelpFolder();
//
// /**
// * Get template type source folder path.
// *
// * @return
// */
// public abstract String getSourceFolder();
//
// /**
// * Get place holder replacer.
// *
// * @return place holder replacer
// */
// public abstract Replacer getPlaceHolderReplacer();
//
// /**
// * Get resource
// *
// * @return resource
// */
// public Resource getResource() {
// return resource;
// }
//
// /**
// * Set global config properties in the resource
// *
// * @param config
// * - properties config
// */
// public void setGlobalConfigProperties(final Config config) {
// // Set extensions from config file
// final String[] extensions = config.getFileExtensions();
// getResource().setExtensions(extensions);
//
// // Set overwriting methods from config file
// if (Constants.EXISTING_DESTINATION_RESOURCES_WARN
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToWarnDestDir(true);
// } else if (Constants.EXISTING_DESTINATION_RESOURCES_DELETE
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToDeleteDestDir(true);
// }
// }
// }
//
// Path: src/main/java/com/headwire/aemdc/runner/HelpRunner.java
// public class HelpRunner extends BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(HelpRunner.class);
// private static final String HELP_FOLDER = "help";
//
// /**
// * Invoker
// */
// private final CommandMenu menu = new CommandMenu();
// private final Config config;
//
// /**
// * Constructor
// *
// * @param resource
// * - resource object
// */
// public HelpRunner(final Resource resource, final Config config) {
// this.resource = resource;
// this.config = config;
//
// LOG.debug("Help runner starting...");
//
// // Creates Invoker object, command object and configure them
// menu.setCommand(1, new HelpCommand(resource, config));
// }
//
// /**
// * Run commands
// *
// * @throws IOException
// */
// @Override
// public void run() throws IOException {
// // Invoker invokes command
// menu.runCommand(1);
// }
//
// @Override
// public String getHelpFolder() {
// return Constants.TYPES_STATIC_FOLDER + "/" + HELP_FOLDER;
// }
//
// @Override
// public String getTemplateHelpFolder() {
// return getHelpFolder();
// }
//
// @Override
// public String getSourceFolder() {
// return resource.getSourceFolderPath();
// }
//
// @Override
// public Replacer getPlaceHolderReplacer() {
// return null;
// }
// }
// Path: src/main/java/com/headwire/aemdc/companion/RunnableCompanion.java
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.headwire.aemdc.runner.BasisRunner;
import com.headwire.aemdc.runner.HelpRunner;
import ch.qos.logback.classic.Level;
package com.headwire.aemdc.companion;
/**
* Runnable Companion Main Class
*
* @author Marat Saitov, 25.10.2016
*/
public class RunnableCompanion {
private static final Logger LOG = LoggerFactory.getLogger(RunnableCompanion.class);
private static final ch.qos.logback.classic.Logger ROOT_LOGGER = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
private static Config config;
/**
* Main start method.
*
* @param args
* - arguments
* @throws IOException
* - IOException
*/
public static void main(final String[] args) throws IOException {
// set default INFO log level to avoid logging from ConfigUtil
ROOT_LOGGER.setLevel(Level.INFO);
// Get Properties Config from config file
config = new Config(args);
// setup custom log level
if (setupCustomLogLevel()) {
// Check configuration from configuration properties file
config.checkConfiguration();
}
// set mandatories from arguments
final Resource resource = new Resource(args);
// Get Runner | BasisRunner runner = new HelpRunner(resource, config); |
headwirecom/aemdc | src/main/java/com/headwire/aemdc/companion/RunnableCompanion.java | // Path: src/main/java/com/headwire/aemdc/runner/BasisRunner.java
// public abstract class BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(BasisRunner.class);
//
// protected Resource resource;
//
// /**
// * Invoker invokes commands here
// *
// * @throws IOException
// */
// public abstract void run() throws IOException;
//
// /**
// * Get help folder name for template type.
// * Help folders files are under /resources/types/<type>/help/..
// * or /aemdc-files/<type>/help/..
// *
// * @return help folder path
// */
// public abstract String getHelpFolder();
//
// /**
// * Get help folder name for template name.
// * Help folders files are under /aemdc-files/<type>/<template name>/help/..
// *
// * @return help folder path
// */
// public abstract String getTemplateHelpFolder();
//
// /**
// * Get template type source folder path.
// *
// * @return
// */
// public abstract String getSourceFolder();
//
// /**
// * Get place holder replacer.
// *
// * @return place holder replacer
// */
// public abstract Replacer getPlaceHolderReplacer();
//
// /**
// * Get resource
// *
// * @return resource
// */
// public Resource getResource() {
// return resource;
// }
//
// /**
// * Set global config properties in the resource
// *
// * @param config
// * - properties config
// */
// public void setGlobalConfigProperties(final Config config) {
// // Set extensions from config file
// final String[] extensions = config.getFileExtensions();
// getResource().setExtensions(extensions);
//
// // Set overwriting methods from config file
// if (Constants.EXISTING_DESTINATION_RESOURCES_WARN
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToWarnDestDir(true);
// } else if (Constants.EXISTING_DESTINATION_RESOURCES_DELETE
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToDeleteDestDir(true);
// }
// }
// }
//
// Path: src/main/java/com/headwire/aemdc/runner/HelpRunner.java
// public class HelpRunner extends BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(HelpRunner.class);
// private static final String HELP_FOLDER = "help";
//
// /**
// * Invoker
// */
// private final CommandMenu menu = new CommandMenu();
// private final Config config;
//
// /**
// * Constructor
// *
// * @param resource
// * - resource object
// */
// public HelpRunner(final Resource resource, final Config config) {
// this.resource = resource;
// this.config = config;
//
// LOG.debug("Help runner starting...");
//
// // Creates Invoker object, command object and configure them
// menu.setCommand(1, new HelpCommand(resource, config));
// }
//
// /**
// * Run commands
// *
// * @throws IOException
// */
// @Override
// public void run() throws IOException {
// // Invoker invokes command
// menu.runCommand(1);
// }
//
// @Override
// public String getHelpFolder() {
// return Constants.TYPES_STATIC_FOLDER + "/" + HELP_FOLDER;
// }
//
// @Override
// public String getTemplateHelpFolder() {
// return getHelpFolder();
// }
//
// @Override
// public String getSourceFolder() {
// return resource.getSourceFolderPath();
// }
//
// @Override
// public Replacer getPlaceHolderReplacer() {
// return null;
// }
// }
| import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.headwire.aemdc.runner.BasisRunner;
import com.headwire.aemdc.runner.HelpRunner;
import ch.qos.logback.classic.Level; | package com.headwire.aemdc.companion;
/**
* Runnable Companion Main Class
*
* @author Marat Saitov, 25.10.2016
*/
public class RunnableCompanion {
private static final Logger LOG = LoggerFactory.getLogger(RunnableCompanion.class);
private static final ch.qos.logback.classic.Logger ROOT_LOGGER = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
private static Config config;
/**
* Main start method.
*
* @param args
* - arguments
* @throws IOException
* - IOException
*/
public static void main(final String[] args) throws IOException {
// set default INFO log level to avoid logging from ConfigUtil
ROOT_LOGGER.setLevel(Level.INFO);
// Get Properties Config from config file
config = new Config(args);
// setup custom log level
if (setupCustomLogLevel()) {
// Check configuration from configuration properties file
config.checkConfiguration();
}
// set mandatories from arguments
final Resource resource = new Resource(args);
// Get Runner | // Path: src/main/java/com/headwire/aemdc/runner/BasisRunner.java
// public abstract class BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(BasisRunner.class);
//
// protected Resource resource;
//
// /**
// * Invoker invokes commands here
// *
// * @throws IOException
// */
// public abstract void run() throws IOException;
//
// /**
// * Get help folder name for template type.
// * Help folders files are under /resources/types/<type>/help/..
// * or /aemdc-files/<type>/help/..
// *
// * @return help folder path
// */
// public abstract String getHelpFolder();
//
// /**
// * Get help folder name for template name.
// * Help folders files are under /aemdc-files/<type>/<template name>/help/..
// *
// * @return help folder path
// */
// public abstract String getTemplateHelpFolder();
//
// /**
// * Get template type source folder path.
// *
// * @return
// */
// public abstract String getSourceFolder();
//
// /**
// * Get place holder replacer.
// *
// * @return place holder replacer
// */
// public abstract Replacer getPlaceHolderReplacer();
//
// /**
// * Get resource
// *
// * @return resource
// */
// public Resource getResource() {
// return resource;
// }
//
// /**
// * Set global config properties in the resource
// *
// * @param config
// * - properties config
// */
// public void setGlobalConfigProperties(final Config config) {
// // Set extensions from config file
// final String[] extensions = config.getFileExtensions();
// getResource().setExtensions(extensions);
//
// // Set overwriting methods from config file
// if (Constants.EXISTING_DESTINATION_RESOURCES_WARN
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToWarnDestDir(true);
// } else if (Constants.EXISTING_DESTINATION_RESOURCES_DELETE
// .equals(config.getProperty(Constants.CONFIGPROP_EXISTING_DESTINATION_RESOURCES_REPLACEMENT))) {
// getResource().setToDeleteDestDir(true);
// }
// }
// }
//
// Path: src/main/java/com/headwire/aemdc/runner/HelpRunner.java
// public class HelpRunner extends BasisRunner {
//
// private static final Logger LOG = LoggerFactory.getLogger(HelpRunner.class);
// private static final String HELP_FOLDER = "help";
//
// /**
// * Invoker
// */
// private final CommandMenu menu = new CommandMenu();
// private final Config config;
//
// /**
// * Constructor
// *
// * @param resource
// * - resource object
// */
// public HelpRunner(final Resource resource, final Config config) {
// this.resource = resource;
// this.config = config;
//
// LOG.debug("Help runner starting...");
//
// // Creates Invoker object, command object and configure them
// menu.setCommand(1, new HelpCommand(resource, config));
// }
//
// /**
// * Run commands
// *
// * @throws IOException
// */
// @Override
// public void run() throws IOException {
// // Invoker invokes command
// menu.runCommand(1);
// }
//
// @Override
// public String getHelpFolder() {
// return Constants.TYPES_STATIC_FOLDER + "/" + HELP_FOLDER;
// }
//
// @Override
// public String getTemplateHelpFolder() {
// return getHelpFolder();
// }
//
// @Override
// public String getSourceFolder() {
// return resource.getSourceFolderPath();
// }
//
// @Override
// public Replacer getPlaceHolderReplacer() {
// return null;
// }
// }
// Path: src/main/java/com/headwire/aemdc/companion/RunnableCompanion.java
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.headwire.aemdc.runner.BasisRunner;
import com.headwire.aemdc.runner.HelpRunner;
import ch.qos.logback.classic.Level;
package com.headwire.aemdc.companion;
/**
* Runnable Companion Main Class
*
* @author Marat Saitov, 25.10.2016
*/
public class RunnableCompanion {
private static final Logger LOG = LoggerFactory.getLogger(RunnableCompanion.class);
private static final ch.qos.logback.classic.Logger ROOT_LOGGER = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
private static Config config;
/**
* Main start method.
*
* @param args
* - arguments
* @throws IOException
* - IOException
*/
public static void main(final String[] args) throws IOException {
// set default INFO log level to avoid logging from ConfigUtil
ROOT_LOGGER.setLevel(Level.INFO);
// Get Properties Config from config file
config = new Config(args);
// setup custom log level
if (setupCustomLogLevel()) {
// Check configuration from configuration properties file
config.checkConfiguration();
}
// set mandatories from arguments
final Resource resource = new Resource(args);
// Get Runner | BasisRunner runner = new HelpRunner(resource, config); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/TextUtils.java
// public final class TextUtils {
// private TextUtils() {
// }
//
// public static boolean isEmpty(final CharSequence s) {
// return s == null || s.length() == 0;
// }
//
// public static boolean isBlank(final CharSequence s) {
// if (s == null) {
// return true;
// }
// for (int i = 0; i < s.length(); i++) {
// if (Character.isWhitespace(s.charAt(i))) {
// continue;
// }
// return false;
// }
// return true;
// }
// }
| import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import de.mprengemann.intellij.plugin.androidicons.util.TextUtils;
import java.lang.reflect.Type; | /*
* Copyright 2015 Marc Prengemann
*
* 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 de.mprengemann.intellij.plugin.androidicons.model;
public enum Resolution {
LDPI,
MDPI,
HDPI,
XHDPI,
XXHDPI,
XXXHDPI,
TVDPI,
ANYDPI;
private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
};
public static Resolution[] nonVectorValues() {
return RESOLUTIONS_WITHOUT_SVG;
}
public static Resolution from(String value) { | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/TextUtils.java
// public final class TextUtils {
// private TextUtils() {
// }
//
// public static boolean isEmpty(final CharSequence s) {
// return s == null || s.length() == 0;
// }
//
// public static boolean isBlank(final CharSequence s) {
// if (s == null) {
// return true;
// }
// for (int i = 0; i < s.length(); i++) {
// if (Character.isWhitespace(s.charAt(i))) {
// continue;
// }
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import de.mprengemann.intellij.plugin.androidicons.util.TextUtils;
import java.lang.reflect.Type;
/*
* Copyright 2015 Marc Prengemann
*
* 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 de.mprengemann.intellij.plugin.androidicons.model;
public enum Resolution {
LDPI,
MDPI,
HDPI,
XHDPI,
XXHDPI,
XXXHDPI,
TVDPI,
ANYDPI;
private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
};
public static Resolution[] nonVectorValues() {
return RESOLUTIONS_WITHOUT_SVG;
}
public static Resolution from(String value) { | if (TextUtils.isEmpty(value)) { |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/widgets/ExportNameField.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/TextUtils.java
// public final class TextUtils {
// private TextUtils() {
// }
//
// public static boolean isEmpty(final CharSequence s) {
// return s == null || s.length() == 0;
// }
//
// public static boolean isBlank(final CharSequence s) {
// if (s == null) {
// return true;
// }
// for (int i = 0; i < s.length(); i++) {
// if (Character.isWhitespace(s.charAt(i))) {
// continue;
// }
// return false;
// }
// return true;
// }
// }
| import com.intellij.openapi.ui.Messages;
import de.mprengemann.intellij.plugin.androidicons.util.TextUtils;
import javax.swing.*;
import javax.swing.text.DefaultFormatter;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; | package de.mprengemann.intellij.plugin.androidicons.widgets;
public class ExportNameField extends JFormattedTextField {
public ExportNameField() {
super(new RegexFormatter("[a-z0-9_\\.]+"));
setInputVerifier(new InputVerifier() {
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
if (input instanceof JFormattedTextField) {
final JFormattedTextField ftf = (JFormattedTextField) input;
final JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter(); | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/TextUtils.java
// public final class TextUtils {
// private TextUtils() {
// }
//
// public static boolean isEmpty(final CharSequence s) {
// return s == null || s.length() == 0;
// }
//
// public static boolean isBlank(final CharSequence s) {
// if (s == null) {
// return true;
// }
// for (int i = 0; i < s.length(); i++) {
// if (Character.isWhitespace(s.charAt(i))) {
// continue;
// }
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/widgets/ExportNameField.java
import com.intellij.openapi.ui.Messages;
import de.mprengemann.intellij.plugin.androidicons.util.TextUtils;
import javax.swing.*;
import javax.swing.text.DefaultFormatter;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
package de.mprengemann.intellij.plugin.androidicons.widgets;
public class ExportNameField extends JFormattedTextField {
public ExportNameField() {
super(new RegexFormatter("[a-z0-9_\\.]+"));
setInputVerifier(new InputVerifier() {
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
if (input instanceof JFormattedTextField) {
final JFormattedTextField ftf = (JFormattedTextField) input;
final JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter(); | if (formatter != null && !TextUtils.isEmpty(ftf.getText())) { |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/IIconPackController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.io.File;
import java.util.List; | package de.mprengemann.intellij.plugin.androidicons.controllers.icons;
public interface IIconPackController {
String getId();
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/IIconPackController.java
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.io.File;
import java.util.List;
package de.mprengemann.intellij.plugin.androidicons.controllers.icons;
public interface IIconPackController {
String getId();
| List<ImageAsset> getAssets(String category); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/IIconPackController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.io.File;
import java.util.List; | package de.mprengemann.intellij.plugin.androidicons.controllers.icons;
public interface IIconPackController {
String getId();
List<ImageAsset> getAssets(String category);
List<ImageAsset> getAssets(List<String> categories);
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/IIconPackController.java
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.io.File;
import java.util.List;
package de.mprengemann.intellij.plugin.androidicons.controllers.icons;
public interface IIconPackController {
String getId();
List<ImageAsset> getAssets(String category);
List<ImageAsset> getAssets(List<String> categories);
| File getImageFile(ImageAsset asset, String color, Resolution resolution); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/androidicons/AndroidIconsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
| import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.List;
import java.util.Locale; | package de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons;
public class AndroidIconsController implements IAndroidIconsController {
private IconPack iconPack;
public AndroidIconsController(IconPack iconPack) {
this.iconPack = iconPack;
}
@Override
public String getId() {
return iconPack.getId();
}
@Override
public IconPack getIconPack() {
return iconPack;
}
@Override
public boolean supportsVectors() {
return false;
}
@Override | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/androidicons/AndroidIconsController.java
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.List;
import java.util.Locale;
package de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons;
public class AndroidIconsController implements IAndroidIconsController {
private IconPack iconPack;
public AndroidIconsController(IconPack iconPack) {
this.iconPack = iconPack;
}
@Override
public String getId() {
return iconPack.getId();
}
@Override
public IconPack getIconPack() {
return iconPack;
}
@Override
public boolean supportsVectors() {
return false;
}
@Override | public Resolution getThumbnailResolution() { |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/androidicons/AndroidIconsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
| import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.List;
import java.util.Locale; | package de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons;
public class AndroidIconsController implements IAndroidIconsController {
private IconPack iconPack;
public AndroidIconsController(IconPack iconPack) {
this.iconPack = iconPack;
}
@Override
public String getId() {
return iconPack.getId();
}
@Override
public IconPack getIconPack() {
return iconPack;
}
@Override
public boolean supportsVectors() {
return false;
}
@Override
public Resolution getThumbnailResolution() {
return Resolution.LDPI;
}
@Override | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/androidicons/AndroidIconsController.java
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.List;
import java.util.Locale;
package de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons;
public class AndroidIconsController implements IAndroidIconsController {
private IconPack iconPack;
public AndroidIconsController(IconPack iconPack) {
this.iconPack = iconPack;
}
@Override
public String getId() {
return iconPack.getId();
}
@Override
public IconPack getIconPack() {
return iconPack;
}
@Override
public boolean supportsVectors() {
return false;
}
@Override
public Resolution getThumbnailResolution() {
return Resolution.LDPI;
}
@Override | public List<ImageAsset> getAssets(String category) { |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/androidicons/AndroidIconsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
| import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.List;
import java.util.Locale; |
@Override
public List<ImageAsset> getAssets(String category) {
return iconPack.getAssets();
}
@Override
public List<ImageAsset> getAssets(List<String> categories) {
return iconPack.getAssets();
}
@Override
public List<String> getCategories() {
return iconPack.getCategories();
}
@Override
public File getImageFile(ImageAsset asset, String color, Resolution resolution) {
return getImageFile(asset, color, null, resolution);
}
@Override
public File getImageFile(ImageAsset asset, String color, String size, Resolution resolution) {
if (resolution == Resolution.ANYDPI) {
throw new IllegalStateException("Vectors not supported by AndroidIcons");
}
final String localPath = String.format("%s/%s/%s.png",
color,
resolution.toString().toLowerCase(Locale.ENGLISH),
asset.getName()); | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/androidicons/AndroidIconsController.java
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.List;
import java.util.Locale;
@Override
public List<ImageAsset> getAssets(String category) {
return iconPack.getAssets();
}
@Override
public List<ImageAsset> getAssets(List<String> categories) {
return iconPack.getAssets();
}
@Override
public List<String> getCategories() {
return iconPack.getCategories();
}
@Override
public File getImageFile(ImageAsset asset, String color, Resolution resolution) {
return getImageFile(asset, color, null, resolution);
}
@Override
public File getImageFile(ImageAsset asset, String color, String size, Resolution resolution) {
if (resolution == Resolution.ANYDPI) {
throw new IllegalStateException("Vectors not supported by AndroidIcons");
}
final String localPath = String.format("%s/%s/%s.png",
color,
resolution.toString().toLowerCase(Locale.ENGLISH),
asset.getName()); | return ResourceLoader.getAssetResource(new File(iconPack.getPath(), localPath).getPath()); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.defaults;
public interface IDefaultsController {
Set<Resolution> getResolutions();
void setResolutions(Set<Resolution> resolutions);
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set;
package de.mprengemann.intellij.plugin.androidicons.controllers.defaults;
public interface IDefaultsController {
Set<Resolution> getResolutions();
void setResolutions(Set<Resolution> resolutions);
| ImageAsset getImageAsset(); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.defaults;
public interface IDefaultsController {
Set<Resolution> getResolutions();
void setResolutions(Set<Resolution> resolutions);
ImageAsset getImageAsset();
void setImageAsset(ImageAsset imageAsset);
Resolution getSourceResolution();
void setSourceResolution(Resolution sourceResolution);
String getSize();
void setSize(String size);
String getColor();
void setColor(String color);
ResizeAlgorithm getAlgorithm();
void setAlgorithm(ResizeAlgorithm algorithm);
String getMethod();
void setMethod(String method);
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set;
package de.mprengemann.intellij.plugin.androidicons.controllers.defaults;
public interface IDefaultsController {
Set<Resolution> getResolutions();
void setResolutions(Set<Resolution> resolutions);
ImageAsset getImageAsset();
void setImageAsset(ImageAsset imageAsset);
Resolution getSourceResolution();
void setSourceResolution(Resolution sourceResolution);
String getSize();
void setSize(String size);
String getColor();
void setColor(String color);
ResizeAlgorithm getAlgorithm();
void setAlgorithm(ResizeAlgorithm algorithm);
String getMethod();
void setMethod(String method);
| Format getFormat(); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.defaults;
public interface IDefaultsController {
Set<Resolution> getResolutions();
void setResolutions(Set<Resolution> resolutions);
ImageAsset getImageAsset();
void setImageAsset(ImageAsset imageAsset);
Resolution getSourceResolution();
void setSourceResolution(Resolution sourceResolution);
String getSize();
void setSize(String size);
String getColor();
void setColor(String color);
ResizeAlgorithm getAlgorithm();
void setAlgorithm(ResizeAlgorithm algorithm);
String getMethod();
void setMethod(String method);
Format getFormat();
void setFormat(Format format);
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set;
package de.mprengemann.intellij.plugin.androidicons.controllers.defaults;
public interface IDefaultsController {
Set<Resolution> getResolutions();
void setResolutions(Set<Resolution> resolutions);
ImageAsset getImageAsset();
void setImageAsset(ImageAsset imageAsset);
Resolution getSourceResolution();
void setSourceResolution(Resolution sourceResolution);
String getSize();
void setSize(String size);
String getColor();
void setColor(String color);
ResizeAlgorithm getAlgorithm();
void setAlgorithm(ResizeAlgorithm algorithm);
String getMethod();
void setMethod(String method);
Format getFormat();
void setFormat(Format format);
| Destination getDestination(); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageInformation.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/DefaultsController.java
// public class DefaultsController implements IDefaultsController {
//
// public static final HashSet<Resolution> DEFAULT_RESOLUTIONS = new HashSet<Resolution>(Arrays.asList(Resolution.MDPI,
// Resolution.HDPI,
// Resolution.XHDPI,
// Resolution.XXHDPI,
// Resolution.XXXHDPI));
// public static final Resolution DEFAULT_SOURCE_RESOLUTION = Resolution.XHDPI;
// public static final ResizeAlgorithm DEFAULT_ALGORITHM = ResizeAlgorithm.SCALR;
// public static final String DEFAULT_METHOD = DEFAULT_ALGORITHM.getMethods().get(0);
// public static final Format DEFAULT_FORMAT = Format.PNG;
// public static final Destination DEFAULT_DESTINATION = Destination.DRAWABLE;
//
// private Set<Resolution> resolutions;
// private Resolution sourceResolution;
//
// private ImageAsset imageAsset;
// private ISettingsController settingsController;
//
// private ResizeAlgorithm algorithm;
// private String method;
// private Format format;
// private Destination destination;
//
// private String size;
// private String color;
//
// public DefaultsController(ISettingsController settingsController) {
// this.settingsController = settingsController;
// }
//
// @Override
// public Set<Resolution> getResolutions() {
// return resolutions;
// }
//
// @Override
// public void setResolutions(Set<Resolution> resolutions) {
// this.resolutions = resolutions;
// settingsController.saveResolutions(this.resolutions);
// }
//
// @Override
// public ImageAsset getImageAsset() {
// return imageAsset;
// }
//
// @Override
// public void setImageAsset(ImageAsset imageAsset) {
// this.imageAsset = imageAsset;
// settingsController.saveImageAsset(this.imageAsset);
// }
//
// @Override
// public Resolution getSourceResolution() {
// return sourceResolution;
// }
//
// @Override
// public void setSourceResolution(Resolution sourceResolution) {
// this.sourceResolution = sourceResolution;
// settingsController.saveSourceResolution(this.sourceResolution);
// }
//
// @Override
// public String getSize() {
// return size;
// }
//
// @Override
// public void setSize(String size) {
// this.size = size;
// settingsController.saveSize(this.size);
// }
//
// @Override
// public String getColor() {
// return color;
// }
//
// @Override
// public void setColor(String color) {
// this.color = color;
// settingsController.saveColor(this.color);
// }
//
// @Override
// public ResizeAlgorithm getAlgorithm() {
// return algorithm;
// }
//
// @Override
// public void setAlgorithm(ResizeAlgorithm algorithm) {
// this.algorithm = algorithm;
// settingsController.saveAlgorithm(this.algorithm);
// }
//
// @Override
// public String getMethod() {
// return method;
// }
//
// @Override
// public void setMethod(String method) {
// this.method = method;
// settingsController.saveMethod(this.method);
// }
//
// @Override
// public Format getFormat() {
// return format;
// }
//
// @Override
// public void setFormat(Format format) {
// this.format = format;
// settingsController.saveFormat(this.format);
// }
//
// @Override
// public Destination getDestination() {
// return destination;
// }
//
// @Override
// public void setDestination(Destination destination) {
// this.destination = destination;
// settingsController.saveDestination(this.destination);
// }
//
// @Override
// public void restore() {
// imageAsset = settingsController.getImageAsset();
// resolutions = settingsController.getResolutions(DEFAULT_RESOLUTIONS);
// sourceResolution = settingsController.getSourceResolution(DEFAULT_SOURCE_RESOLUTION);
// algorithm = settingsController.getAlgorithm(DEFAULT_ALGORITHM);
// format = settingsController.getFormat(DEFAULT_FORMAT);
// destination = settingsController.getDestination(DEFAULT_DESTINATION);
// method = settingsController.getMethod(DEFAULT_METHOD);
// color = settingsController.getColor();
// size = settingsController.getSize();
// }
//
// @Override
// public void tearDown() {
// resolutions = null;
// imageAsset = null;
// sourceResolution = null;
// size = null;
// color = null;
// algorithm = null;
// format = null;
// destination = null;
// method = null;
// settingsController = null;
// }
// }
| import com.intellij.openapi.application.PathManager;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.DefaultsController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import java.io.File;
import java.util.Locale; | }
public Destination getDestination() {
return destination;
}
public File getTargetFile() {
return new File(String.format(TARGET_FILE_PATTERN,
exportPath,
destination.getFolderName(),
targetResolution.toString().toLowerCase(Locale.ENGLISH),
exportName,
format.toString().toLowerCase()));
}
public boolean isVector() {
return vector;
}
public static class Builder {
private File imageFile = null;
private String exportPath = null;
private String exportName = null;
private float factor = 1f;
// Optional parameters
private boolean ninePatch = false;
private boolean vector = false;
private Resolution targetResolution = Resolution.XHDPI; | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/DefaultsController.java
// public class DefaultsController implements IDefaultsController {
//
// public static final HashSet<Resolution> DEFAULT_RESOLUTIONS = new HashSet<Resolution>(Arrays.asList(Resolution.MDPI,
// Resolution.HDPI,
// Resolution.XHDPI,
// Resolution.XXHDPI,
// Resolution.XXXHDPI));
// public static final Resolution DEFAULT_SOURCE_RESOLUTION = Resolution.XHDPI;
// public static final ResizeAlgorithm DEFAULT_ALGORITHM = ResizeAlgorithm.SCALR;
// public static final String DEFAULT_METHOD = DEFAULT_ALGORITHM.getMethods().get(0);
// public static final Format DEFAULT_FORMAT = Format.PNG;
// public static final Destination DEFAULT_DESTINATION = Destination.DRAWABLE;
//
// private Set<Resolution> resolutions;
// private Resolution sourceResolution;
//
// private ImageAsset imageAsset;
// private ISettingsController settingsController;
//
// private ResizeAlgorithm algorithm;
// private String method;
// private Format format;
// private Destination destination;
//
// private String size;
// private String color;
//
// public DefaultsController(ISettingsController settingsController) {
// this.settingsController = settingsController;
// }
//
// @Override
// public Set<Resolution> getResolutions() {
// return resolutions;
// }
//
// @Override
// public void setResolutions(Set<Resolution> resolutions) {
// this.resolutions = resolutions;
// settingsController.saveResolutions(this.resolutions);
// }
//
// @Override
// public ImageAsset getImageAsset() {
// return imageAsset;
// }
//
// @Override
// public void setImageAsset(ImageAsset imageAsset) {
// this.imageAsset = imageAsset;
// settingsController.saveImageAsset(this.imageAsset);
// }
//
// @Override
// public Resolution getSourceResolution() {
// return sourceResolution;
// }
//
// @Override
// public void setSourceResolution(Resolution sourceResolution) {
// this.sourceResolution = sourceResolution;
// settingsController.saveSourceResolution(this.sourceResolution);
// }
//
// @Override
// public String getSize() {
// return size;
// }
//
// @Override
// public void setSize(String size) {
// this.size = size;
// settingsController.saveSize(this.size);
// }
//
// @Override
// public String getColor() {
// return color;
// }
//
// @Override
// public void setColor(String color) {
// this.color = color;
// settingsController.saveColor(this.color);
// }
//
// @Override
// public ResizeAlgorithm getAlgorithm() {
// return algorithm;
// }
//
// @Override
// public void setAlgorithm(ResizeAlgorithm algorithm) {
// this.algorithm = algorithm;
// settingsController.saveAlgorithm(this.algorithm);
// }
//
// @Override
// public String getMethod() {
// return method;
// }
//
// @Override
// public void setMethod(String method) {
// this.method = method;
// settingsController.saveMethod(this.method);
// }
//
// @Override
// public Format getFormat() {
// return format;
// }
//
// @Override
// public void setFormat(Format format) {
// this.format = format;
// settingsController.saveFormat(this.format);
// }
//
// @Override
// public Destination getDestination() {
// return destination;
// }
//
// @Override
// public void setDestination(Destination destination) {
// this.destination = destination;
// settingsController.saveDestination(this.destination);
// }
//
// @Override
// public void restore() {
// imageAsset = settingsController.getImageAsset();
// resolutions = settingsController.getResolutions(DEFAULT_RESOLUTIONS);
// sourceResolution = settingsController.getSourceResolution(DEFAULT_SOURCE_RESOLUTION);
// algorithm = settingsController.getAlgorithm(DEFAULT_ALGORITHM);
// format = settingsController.getFormat(DEFAULT_FORMAT);
// destination = settingsController.getDestination(DEFAULT_DESTINATION);
// method = settingsController.getMethod(DEFAULT_METHOD);
// color = settingsController.getColor();
// size = settingsController.getSize();
// }
//
// @Override
// public void tearDown() {
// resolutions = null;
// imageAsset = null;
// sourceResolution = null;
// size = null;
// color = null;
// algorithm = null;
// format = null;
// destination = null;
// method = null;
// settingsController = null;
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageInformation.java
import com.intellij.openapi.application.PathManager;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.DefaultsController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import java.io.File;
import java.util.Locale;
}
public Destination getDestination() {
return destination;
}
public File getTargetFile() {
return new File(String.format(TARGET_FILE_PATTERN,
exportPath,
destination.getFolderName(),
targetResolution.toString().toLowerCase(Locale.ENGLISH),
exportName,
format.toString().toLowerCase()));
}
public boolean isVector() {
return vector;
}
public static class Builder {
private File imageFile = null;
private String exportPath = null;
private String exportName = null;
private float factor = 1f;
// Optional parameters
private boolean ninePatch = false;
private boolean vector = false;
private Resolution targetResolution = Resolution.XHDPI; | private ResizeAlgorithm algorithm = DefaultsController.DEFAULT_ALGORITHM; |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IControllerFactory.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
// public interface IDefaultsController {
// Set<Resolution> getResolutions();
// void setResolutions(Set<Resolution> resolutions);
//
// ImageAsset getImageAsset();
// void setImageAsset(ImageAsset imageAsset);
//
// Resolution getSourceResolution();
// void setSourceResolution(Resolution sourceResolution);
//
// String getSize();
// void setSize(String size);
//
// String getColor();
// void setColor(String color);
//
// ResizeAlgorithm getAlgorithm();
// void setAlgorithm(ResizeAlgorithm algorithm);
//
// String getMethod();
// void setMethod(String method);
//
// Format getFormat();
// void setFormat(Format format);
//
// Destination getDestination();
// void setDestination(Destination destination);
//
// void restore();
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/IMaterialIconsController.java
// public interface IMaterialIconsController extends IIconPackController {
// void openHelp();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
// public interface ISettingsController extends IController<SettingsObserver> {
// void saveResRootForProject(String fileUrl);
// VirtualFile getResourceRoot();
// String getResourceRootPath();
//
// String getLastImageFolder();
// void saveLastImageFolder(String fileUrl);
//
// void setProject(Project project);
//
// void saveResolutions(Set<Resolution> resolutions);
// Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
//
// void saveSourceResolution(Resolution sourceResolution);
// Resolution getSourceResolution(Resolution defaultSourceResolution);
//
// void saveAlgorithm(ResizeAlgorithm algorithm);
// ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
//
// void saveMethod(String method);
// String getMethod(String defaultMethod);
//
// void saveColor(String color);
// String getColor();
//
// void saveSize(String size);
// String getSize();
//
// void saveImageAsset(ImageAsset imageAsset);
// ImageAsset getImageAsset();
//
// void saveFormat(Format format);
// Format getFormat(Format defaultFormat);
//
// void saveDestination(Destination destination);
// Destination getDestination(Destination defaultDestination);
//
// }
| import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.IDefaultsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons.IAndroidIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons.IMaterialIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.settings.ISettingsController; | package de.mprengemann.intellij.plugin.androidicons.controllers;
public interface IControllerFactory {
void setProject(Project project);
IAndroidIconsController getAndroidIconsController();
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
// public interface IDefaultsController {
// Set<Resolution> getResolutions();
// void setResolutions(Set<Resolution> resolutions);
//
// ImageAsset getImageAsset();
// void setImageAsset(ImageAsset imageAsset);
//
// Resolution getSourceResolution();
// void setSourceResolution(Resolution sourceResolution);
//
// String getSize();
// void setSize(String size);
//
// String getColor();
// void setColor(String color);
//
// ResizeAlgorithm getAlgorithm();
// void setAlgorithm(ResizeAlgorithm algorithm);
//
// String getMethod();
// void setMethod(String method);
//
// Format getFormat();
// void setFormat(Format format);
//
// Destination getDestination();
// void setDestination(Destination destination);
//
// void restore();
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/IMaterialIconsController.java
// public interface IMaterialIconsController extends IIconPackController {
// void openHelp();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
// public interface ISettingsController extends IController<SettingsObserver> {
// void saveResRootForProject(String fileUrl);
// VirtualFile getResourceRoot();
// String getResourceRootPath();
//
// String getLastImageFolder();
// void saveLastImageFolder(String fileUrl);
//
// void setProject(Project project);
//
// void saveResolutions(Set<Resolution> resolutions);
// Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
//
// void saveSourceResolution(Resolution sourceResolution);
// Resolution getSourceResolution(Resolution defaultSourceResolution);
//
// void saveAlgorithm(ResizeAlgorithm algorithm);
// ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
//
// void saveMethod(String method);
// String getMethod(String defaultMethod);
//
// void saveColor(String color);
// String getColor();
//
// void saveSize(String size);
// String getSize();
//
// void saveImageAsset(ImageAsset imageAsset);
// ImageAsset getImageAsset();
//
// void saveFormat(Format format);
// Format getFormat(Format defaultFormat);
//
// void saveDestination(Destination destination);
// Destination getDestination(Destination defaultDestination);
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IControllerFactory.java
import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.IDefaultsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons.IAndroidIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons.IMaterialIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.settings.ISettingsController;
package de.mprengemann.intellij.plugin.androidicons.controllers;
public interface IControllerFactory {
void setProject(Project project);
IAndroidIconsController getAndroidIconsController();
| IMaterialIconsController getMaterialIconsController(); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IControllerFactory.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
// public interface IDefaultsController {
// Set<Resolution> getResolutions();
// void setResolutions(Set<Resolution> resolutions);
//
// ImageAsset getImageAsset();
// void setImageAsset(ImageAsset imageAsset);
//
// Resolution getSourceResolution();
// void setSourceResolution(Resolution sourceResolution);
//
// String getSize();
// void setSize(String size);
//
// String getColor();
// void setColor(String color);
//
// ResizeAlgorithm getAlgorithm();
// void setAlgorithm(ResizeAlgorithm algorithm);
//
// String getMethod();
// void setMethod(String method);
//
// Format getFormat();
// void setFormat(Format format);
//
// Destination getDestination();
// void setDestination(Destination destination);
//
// void restore();
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/IMaterialIconsController.java
// public interface IMaterialIconsController extends IIconPackController {
// void openHelp();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
// public interface ISettingsController extends IController<SettingsObserver> {
// void saveResRootForProject(String fileUrl);
// VirtualFile getResourceRoot();
// String getResourceRootPath();
//
// String getLastImageFolder();
// void saveLastImageFolder(String fileUrl);
//
// void setProject(Project project);
//
// void saveResolutions(Set<Resolution> resolutions);
// Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
//
// void saveSourceResolution(Resolution sourceResolution);
// Resolution getSourceResolution(Resolution defaultSourceResolution);
//
// void saveAlgorithm(ResizeAlgorithm algorithm);
// ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
//
// void saveMethod(String method);
// String getMethod(String defaultMethod);
//
// void saveColor(String color);
// String getColor();
//
// void saveSize(String size);
// String getSize();
//
// void saveImageAsset(ImageAsset imageAsset);
// ImageAsset getImageAsset();
//
// void saveFormat(Format format);
// Format getFormat(Format defaultFormat);
//
// void saveDestination(Destination destination);
// Destination getDestination(Destination defaultDestination);
//
// }
| import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.IDefaultsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons.IAndroidIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons.IMaterialIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.settings.ISettingsController; | package de.mprengemann.intellij.plugin.androidicons.controllers;
public interface IControllerFactory {
void setProject(Project project);
IAndroidIconsController getAndroidIconsController();
IMaterialIconsController getMaterialIconsController();
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
// public interface IDefaultsController {
// Set<Resolution> getResolutions();
// void setResolutions(Set<Resolution> resolutions);
//
// ImageAsset getImageAsset();
// void setImageAsset(ImageAsset imageAsset);
//
// Resolution getSourceResolution();
// void setSourceResolution(Resolution sourceResolution);
//
// String getSize();
// void setSize(String size);
//
// String getColor();
// void setColor(String color);
//
// ResizeAlgorithm getAlgorithm();
// void setAlgorithm(ResizeAlgorithm algorithm);
//
// String getMethod();
// void setMethod(String method);
//
// Format getFormat();
// void setFormat(Format format);
//
// Destination getDestination();
// void setDestination(Destination destination);
//
// void restore();
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/IMaterialIconsController.java
// public interface IMaterialIconsController extends IIconPackController {
// void openHelp();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
// public interface ISettingsController extends IController<SettingsObserver> {
// void saveResRootForProject(String fileUrl);
// VirtualFile getResourceRoot();
// String getResourceRootPath();
//
// String getLastImageFolder();
// void saveLastImageFolder(String fileUrl);
//
// void setProject(Project project);
//
// void saveResolutions(Set<Resolution> resolutions);
// Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
//
// void saveSourceResolution(Resolution sourceResolution);
// Resolution getSourceResolution(Resolution defaultSourceResolution);
//
// void saveAlgorithm(ResizeAlgorithm algorithm);
// ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
//
// void saveMethod(String method);
// String getMethod(String defaultMethod);
//
// void saveColor(String color);
// String getColor();
//
// void saveSize(String size);
// String getSize();
//
// void saveImageAsset(ImageAsset imageAsset);
// ImageAsset getImageAsset();
//
// void saveFormat(Format format);
// Format getFormat(Format defaultFormat);
//
// void saveDestination(Destination destination);
// Destination getDestination(Destination defaultDestination);
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IControllerFactory.java
import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.IDefaultsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons.IAndroidIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons.IMaterialIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.settings.ISettingsController;
package de.mprengemann.intellij.plugin.androidicons.controllers;
public interface IControllerFactory {
void setProject(Project project);
IAndroidIconsController getAndroidIconsController();
IMaterialIconsController getMaterialIconsController();
| IDefaultsController getDefaultsController(); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IControllerFactory.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
// public interface IDefaultsController {
// Set<Resolution> getResolutions();
// void setResolutions(Set<Resolution> resolutions);
//
// ImageAsset getImageAsset();
// void setImageAsset(ImageAsset imageAsset);
//
// Resolution getSourceResolution();
// void setSourceResolution(Resolution sourceResolution);
//
// String getSize();
// void setSize(String size);
//
// String getColor();
// void setColor(String color);
//
// ResizeAlgorithm getAlgorithm();
// void setAlgorithm(ResizeAlgorithm algorithm);
//
// String getMethod();
// void setMethod(String method);
//
// Format getFormat();
// void setFormat(Format format);
//
// Destination getDestination();
// void setDestination(Destination destination);
//
// void restore();
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/IMaterialIconsController.java
// public interface IMaterialIconsController extends IIconPackController {
// void openHelp();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
// public interface ISettingsController extends IController<SettingsObserver> {
// void saveResRootForProject(String fileUrl);
// VirtualFile getResourceRoot();
// String getResourceRootPath();
//
// String getLastImageFolder();
// void saveLastImageFolder(String fileUrl);
//
// void setProject(Project project);
//
// void saveResolutions(Set<Resolution> resolutions);
// Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
//
// void saveSourceResolution(Resolution sourceResolution);
// Resolution getSourceResolution(Resolution defaultSourceResolution);
//
// void saveAlgorithm(ResizeAlgorithm algorithm);
// ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
//
// void saveMethod(String method);
// String getMethod(String defaultMethod);
//
// void saveColor(String color);
// String getColor();
//
// void saveSize(String size);
// String getSize();
//
// void saveImageAsset(ImageAsset imageAsset);
// ImageAsset getImageAsset();
//
// void saveFormat(Format format);
// Format getFormat(Format defaultFormat);
//
// void saveDestination(Destination destination);
// Destination getDestination(Destination defaultDestination);
//
// }
| import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.IDefaultsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons.IAndroidIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons.IMaterialIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.settings.ISettingsController; | package de.mprengemann.intellij.plugin.androidicons.controllers;
public interface IControllerFactory {
void setProject(Project project);
IAndroidIconsController getAndroidIconsController();
IMaterialIconsController getMaterialIconsController();
IDefaultsController getDefaultsController();
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/defaults/IDefaultsController.java
// public interface IDefaultsController {
// Set<Resolution> getResolutions();
// void setResolutions(Set<Resolution> resolutions);
//
// ImageAsset getImageAsset();
// void setImageAsset(ImageAsset imageAsset);
//
// Resolution getSourceResolution();
// void setSourceResolution(Resolution sourceResolution);
//
// String getSize();
// void setSize(String size);
//
// String getColor();
// void setColor(String color);
//
// ResizeAlgorithm getAlgorithm();
// void setAlgorithm(ResizeAlgorithm algorithm);
//
// String getMethod();
// void setMethod(String method);
//
// Format getFormat();
// void setFormat(Format format);
//
// Destination getDestination();
// void setDestination(Destination destination);
//
// void restore();
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/IMaterialIconsController.java
// public interface IMaterialIconsController extends IIconPackController {
// void openHelp();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
// public interface ISettingsController extends IController<SettingsObserver> {
// void saveResRootForProject(String fileUrl);
// VirtualFile getResourceRoot();
// String getResourceRootPath();
//
// String getLastImageFolder();
// void saveLastImageFolder(String fileUrl);
//
// void setProject(Project project);
//
// void saveResolutions(Set<Resolution> resolutions);
// Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
//
// void saveSourceResolution(Resolution sourceResolution);
// Resolution getSourceResolution(Resolution defaultSourceResolution);
//
// void saveAlgorithm(ResizeAlgorithm algorithm);
// ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
//
// void saveMethod(String method);
// String getMethod(String defaultMethod);
//
// void saveColor(String color);
// String getColor();
//
// void saveSize(String size);
// String getSize();
//
// void saveImageAsset(ImageAsset imageAsset);
// ImageAsset getImageAsset();
//
// void saveFormat(Format format);
// Format getFormat(Format defaultFormat);
//
// void saveDestination(Destination destination);
// Destination getDestination(Destination defaultDestination);
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IControllerFactory.java
import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.defaults.IDefaultsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.androidicons.IAndroidIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons.IMaterialIconsController;
import de.mprengemann.intellij.plugin.androidicons.controllers.settings.ISettingsController;
package de.mprengemann.intellij.plugin.androidicons.controllers;
public interface IControllerFactory {
void setProject(Project project);
IAndroidIconsController getAndroidIconsController();
IMaterialIconsController getMaterialIconsController();
IDefaultsController getDefaultsController();
| ISettingsController getSettingsController(); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IController.java
// public interface IController<T> {
// void addObserver(T observer);
//
// void removeObserver(T observer);
//
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.settings;
public interface ISettingsController extends IController<SettingsObserver> {
void saveResRootForProject(String fileUrl);
VirtualFile getResourceRoot();
String getResourceRootPath();
String getLastImageFolder();
void saveLastImageFolder(String fileUrl);
void setProject(Project project);
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IController.java
// public interface IController<T> {
// void addObserver(T observer);
//
// void removeObserver(T observer);
//
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set;
package de.mprengemann.intellij.plugin.androidicons.controllers.settings;
public interface ISettingsController extends IController<SettingsObserver> {
void saveResRootForProject(String fileUrl);
VirtualFile getResourceRoot();
String getResourceRootPath();
String getLastImageFolder();
void saveLastImageFolder(String fileUrl);
void setProject(Project project);
| void saveResolutions(Set<Resolution> resolutions); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IController.java
// public interface IController<T> {
// void addObserver(T observer);
//
// void removeObserver(T observer);
//
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.settings;
public interface ISettingsController extends IController<SettingsObserver> {
void saveResRootForProject(String fileUrl);
VirtualFile getResourceRoot();
String getResourceRootPath();
String getLastImageFolder();
void saveLastImageFolder(String fileUrl);
void setProject(Project project);
void saveResolutions(Set<Resolution> resolutions);
Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
void saveSourceResolution(Resolution sourceResolution);
Resolution getSourceResolution(Resolution defaultSourceResolution);
void saveAlgorithm(ResizeAlgorithm algorithm);
ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
void saveMethod(String method);
String getMethod(String defaultMethod);
void saveColor(String color);
String getColor();
void saveSize(String size);
String getSize();
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IController.java
// public interface IController<T> {
// void addObserver(T observer);
//
// void removeObserver(T observer);
//
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set;
package de.mprengemann.intellij.plugin.androidicons.controllers.settings;
public interface ISettingsController extends IController<SettingsObserver> {
void saveResRootForProject(String fileUrl);
VirtualFile getResourceRoot();
String getResourceRootPath();
String getLastImageFolder();
void saveLastImageFolder(String fileUrl);
void setProject(Project project);
void saveResolutions(Set<Resolution> resolutions);
Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
void saveSourceResolution(Resolution sourceResolution);
Resolution getSourceResolution(Resolution defaultSourceResolution);
void saveAlgorithm(ResizeAlgorithm algorithm);
ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
void saveMethod(String method);
String getMethod(String defaultMethod);
void saveColor(String color);
String getColor();
void saveSize(String size);
String getSize();
| void saveImageAsset(ImageAsset imageAsset); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IController.java
// public interface IController<T> {
// void addObserver(T observer);
//
// void removeObserver(T observer);
//
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.settings;
public interface ISettingsController extends IController<SettingsObserver> {
void saveResRootForProject(String fileUrl);
VirtualFile getResourceRoot();
String getResourceRootPath();
String getLastImageFolder();
void saveLastImageFolder(String fileUrl);
void setProject(Project project);
void saveResolutions(Set<Resolution> resolutions);
Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
void saveSourceResolution(Resolution sourceResolution);
Resolution getSourceResolution(Resolution defaultSourceResolution);
void saveAlgorithm(ResizeAlgorithm algorithm);
ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
void saveMethod(String method);
String getMethod(String defaultMethod);
void saveColor(String color);
String getColor();
void saveSize(String size);
String getSize();
void saveImageAsset(ImageAsset imageAsset);
ImageAsset getImageAsset();
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/IController.java
// public interface IController<T> {
// void addObserver(T observer);
//
// void removeObserver(T observer);
//
// void tearDown();
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Destination.java
// public enum Destination {
// DRAWABLE("drawable"),
// MIPMAP("mipmap");
//
//
// private final String folderName;
//
// Destination(String folderName) {
// this.folderName = folderName;
// }
//
// public String getFolderName() {
// return folderName;
// }
//
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Format.java
// public enum Format {
// JPG,
// PNG,
// XML;
//
// private static final Format[] NON_VECTOR_VALUES = new Format[] {
// JPG, PNG
// };
//
// public static Format[] nonVectorValues() {
// return NON_VECTOR_VALUES;
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/settings/ISettingsController.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.ResizeAlgorithm;
import de.mprengemann.intellij.plugin.androidicons.model.Destination;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.util.Set;
package de.mprengemann.intellij.plugin.androidicons.controllers.settings;
public interface ISettingsController extends IController<SettingsObserver> {
void saveResRootForProject(String fileUrl);
VirtualFile getResourceRoot();
String getResourceRootPath();
String getLastImageFolder();
void saveLastImageFolder(String fileUrl);
void setProject(Project project);
void saveResolutions(Set<Resolution> resolutions);
Set<Resolution> getResolutions(Set<Resolution> defaultResolutions);
void saveSourceResolution(Resolution sourceResolution);
Resolution getSourceResolution(Resolution defaultSourceResolution);
void saveAlgorithm(ResizeAlgorithm algorithm);
ResizeAlgorithm getAlgorithm(ResizeAlgorithm defaultAlgorithm);
void saveMethod(String method);
String getMethod(String defaultMethod);
void saveColor(String color);
String getColor();
void saveSize(String size);
String getSize();
void saveImageAsset(ImageAsset imageAsset);
ImageAsset getImageAsset();
| void saveFormat(Format format); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/util/RefactorUtils.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
| import de.mprengemann.intellij.plugin.androidicons.model.Resolution; | /*
* Copyright 2015 Marc Prengemann
*
* 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 de.mprengemann.intellij.plugin.androidicons.util;
public class RefactorUtils {
private static final float FACTOR_LDPI = 0.75f;
private static final float FACTOR_MDPI = 1f;
private static final float FACTOR_HDPI = 1.5f;
private static final float FACTOR_XHDPI = 2f;
private static final float FACTOR_XXHDPI = 3f;
private static final float FACTOR_XXXHDPI = 4f;
private static final float FACTOR_TVDPI = 4f / 3f;
private RefactorUtils() {
}
| // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/RefactorUtils.java
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
/*
* Copyright 2015 Marc Prengemann
*
* 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 de.mprengemann.intellij.plugin.androidicons.util;
public class RefactorUtils {
private static final float FACTOR_LDPI = 0.75f;
private static final float FACTOR_MDPI = 1f;
private static final float FACTOR_HDPI = 1.5f;
private static final float FACTOR_XHDPI = 2f;
private static final float FACTOR_XXHDPI = 3f;
private static final float FACTOR_XXXHDPI = 4f;
private static final float FACTOR_TVDPI = 4f / 3f;
private RefactorUtils() {
}
| public static float getScaleFactor(Resolution target, Resolution baseLine) { |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/actions/AndroidAssetUtilsGroup.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/AndroidFacetUtils.java
// public class AndroidFacetUtils {
// private AndroidFacetUtils() {
// }
//
// public static AndroidFacet getCurrentFacet(Project project, Module module) {
// AndroidFacet currentFacet = null;
// if (module == null) {
// return null;
// }
// List<AndroidFacet> applicationFacets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID);
// for (AndroidFacet facet : applicationFacets) {
// if (facet.getModule().getName().equals(module.getName())) {
// currentFacet = facet;
// break;
// }
// }
// return currentFacet;
// }
//
// public static String getResourcesRoot(Project project, Module module) {
// final AndroidFacet currentFacet = AndroidFacetUtils.getCurrentFacet(project, module);
// final List<VirtualFile> allResourceDirectories = currentFacet.getAllResourceDirectories();
// String exportRoot = "";
// if (allResourceDirectories.size() == 1) {
// exportRoot = allResourceDirectories.get(0).getCanonicalPath();
// }
//
// return exportRoot;
// }
//
// public static void updateActionVisibility(AnActionEvent e) {
// Module module = e.getData(LangDataKeys.MODULE);
// AndroidFacet androidFacet = AndroidFacetUtils.getCurrentFacet(AnAction.getEventProject(e), module);
// e.getPresentation().setVisible(module != null && androidFacet != null);
// }
// }
| import com.intellij.openapi.actionSystem.DefaultActionGroup;
import de.mprengemann.intellij.plugin.androidicons.util.AndroidFacetUtils;
import com.intellij.openapi.actionSystem.AnActionEvent; | /*
* Copyright 2015 Marc Prengemann
*
* 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 de.mprengemann.intellij.plugin.androidicons.actions;
public class AndroidAssetUtilsGroup extends DefaultActionGroup {
@Override
public void update(AnActionEvent e) {
super.update(e); | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/util/AndroidFacetUtils.java
// public class AndroidFacetUtils {
// private AndroidFacetUtils() {
// }
//
// public static AndroidFacet getCurrentFacet(Project project, Module module) {
// AndroidFacet currentFacet = null;
// if (module == null) {
// return null;
// }
// List<AndroidFacet> applicationFacets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID);
// for (AndroidFacet facet : applicationFacets) {
// if (facet.getModule().getName().equals(module.getName())) {
// currentFacet = facet;
// break;
// }
// }
// return currentFacet;
// }
//
// public static String getResourcesRoot(Project project, Module module) {
// final AndroidFacet currentFacet = AndroidFacetUtils.getCurrentFacet(project, module);
// final List<VirtualFile> allResourceDirectories = currentFacet.getAllResourceDirectories();
// String exportRoot = "";
// if (allResourceDirectories.size() == 1) {
// exportRoot = allResourceDirectories.get(0).getCanonicalPath();
// }
//
// return exportRoot;
// }
//
// public static void updateActionVisibility(AnActionEvent e) {
// Module module = e.getData(LangDataKeys.MODULE);
// AndroidFacet androidFacet = AndroidFacetUtils.getCurrentFacet(AnAction.getEventProject(e), module);
// e.getPresentation().setVisible(module != null && androidFacet != null);
// }
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/actions/AndroidAssetUtilsGroup.java
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import de.mprengemann.intellij.plugin.androidicons.util.AndroidFacetUtils;
import com.intellij.openapi.actionSystem.AnActionEvent;
/*
* Copyright 2015 Marc Prengemann
*
* 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 de.mprengemann.intellij.plugin.androidicons.actions;
public class AndroidAssetUtilsGroup extends DefaultActionGroup {
@Override
public void update(AnActionEvent e) {
super.update(e); | AndroidFacetUtils.updateActionVisibility(e); |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/MaterialIconsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
| import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.ide.BrowserUtil;
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; | package de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons;
public class MaterialIconsController implements IMaterialIconsController {
private IconPack iconPack; | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/MaterialIconsController.java
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.ide.BrowserUtil;
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
package de.mprengemann.intellij.plugin.androidicons.controllers.icons.materialicons;
public class MaterialIconsController implements IMaterialIconsController {
private IconPack iconPack; | private Map<String, List<ImageAsset>> categoryMap; |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/MaterialIconsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
| import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.ide.BrowserUtil;
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; | private HashMap<String, List<ImageAsset>> initCategoryMap(IconPack iconPack) {
final HashMap<String, List<ImageAsset>> categoryMap = Maps.newHashMap();
if (iconPack == null) {
return categoryMap;
}
for (String category : iconPack.getCategories()) {
categoryMap.put(category, Lists.<ImageAsset>newArrayList());
}
for (ImageAsset asset : iconPack.getAssets()) {
categoryMap.get(asset.getCategory()).add(asset);
}
return categoryMap;
}
@Override
public String getId() {
return iconPack.getId();
}
@Override
public IconPack getIconPack() {
return iconPack;
}
@Override
public boolean supportsVectors() {
return true;
}
@Override | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/MaterialIconsController.java
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.ide.BrowserUtil;
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
private HashMap<String, List<ImageAsset>> initCategoryMap(IconPack iconPack) {
final HashMap<String, List<ImageAsset>> categoryMap = Maps.newHashMap();
if (iconPack == null) {
return categoryMap;
}
for (String category : iconPack.getCategories()) {
categoryMap.put(category, Lists.<ImageAsset>newArrayList());
}
for (ImageAsset asset : iconPack.getAssets()) {
categoryMap.get(asset.getCategory()).add(asset);
}
return categoryMap;
}
@Override
public String getId() {
return iconPack.getId();
}
@Override
public IconPack getIconPack() {
return iconPack;
}
@Override
public boolean supportsVectors() {
return true;
}
@Override | public Resolution getThumbnailResolution() { |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/MaterialIconsController.java | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
| import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.ide.BrowserUtil;
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; | }
@Override
public List<ImageAsset> getAssets(List<String> categories) {
return iconPack.getAssets();
}
@Override
public List<String> getCategories() {
return iconPack.getCategories();
}
@Override
public void openHelp() {
BrowserUtil.browse(iconPack.getUrl());
}
@Override
public File getImageFile(ImageAsset asset, String color, Resolution resolution) {
return getImageFile(asset, color, "24dp", resolution);
}
@Override
public File getImageFile(ImageAsset asset, String color, String size, Resolution resolution) {
final String localPath;
if (resolution == Resolution.ANYDPI) {
localPath = getVectorFilePath(asset);
} else {
localPath = getImageFilePath(asset, color, size, resolution);
} | // Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/ImageAsset.java
// public class ImageAsset implements Comparable<ImageAsset>,
// Serializable {
//
// private final String name;
// private final String pack;
// private final String category;
// private final List<Resolution> resolutions;
// private final List<String> colors;
// private final List<String> sizes;
//
// public ImageAsset(String name,
// String pack,
// String category,
// List<Resolution> resolutions,
// List<String> colors,
// List<String> sizes) {
// this.name = name;
// this.pack = pack;
// this.category = category;
// this.resolutions = resolutions;
// this.colors = colors;
// this.sizes = sizes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getIconPack() {
// return pack;
// }
//
// public String getCategory() {
// return category;
// }
//
// public List<Resolution> getResolutions() {
// return resolutions;
// }
//
// public List<String> getColors() {
// return colors;
// }
//
// public List<String> getSizes() {
// return sizes;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int compareTo(@NotNull ImageAsset o) {
// return getName().compareTo(o.getName());
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/model/Resolution.java
// public enum Resolution {
// LDPI,
// MDPI,
// HDPI,
// XHDPI,
// XXHDPI,
// XXXHDPI,
// TVDPI,
// ANYDPI;
//
// private static final Resolution[] RESOLUTIONS_WITHOUT_SVG = new Resolution[] {
// LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI, TVDPI
// };
//
// public static Resolution[] nonVectorValues() {
// return RESOLUTIONS_WITHOUT_SVG;
// }
//
// public static Resolution from(String value) {
// if (TextUtils.isEmpty(value)) {
// throw new IllegalArgumentException();
// }
// if (value.equalsIgnoreCase(LDPI.toString())) {
// return LDPI;
// } else if (value.equalsIgnoreCase(MDPI.toString())) {
// return MDPI;
// } else if (value.equalsIgnoreCase(HDPI.toString())) {
// return HDPI;
// } else if (value.equalsIgnoreCase(XHDPI.toString())) {
// return XHDPI;
// } else if (value.equalsIgnoreCase(XXHDPI.toString())) {
// return XXHDPI;
// } else if (value.equalsIgnoreCase(XXXHDPI.toString())) {
// return XXXHDPI;
// } else if (value.equalsIgnoreCase(TVDPI.toString())) {
// return TVDPI;
// } else if (value.equalsIgnoreCase(ANYDPI.toString())) {
// return ANYDPI;
// }
// return null;
// }
//
// public static class Deserializer implements JsonDeserializer<Resolution> {
// @Override
// public Resolution deserialize(JsonElement jsonElement,
// Type type,
// JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// return Resolution.from(jsonElement.getAsString());
// }
// }
// }
//
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/resources/ResourceLoader.java
// public class ResourceLoader {
//
// private static final String TAG = ResourceLoader.class.getSimpleName();
// private static final Logger LOGGER = Logger.getInstance(TAG);
//
// static ResourceLoader rl = new ResourceLoader();
//
// public static File getExportPath() {
// final String exportPath = PathManager.getSystemPath();
// return new File(exportPath, "android-drawable-importer-intellij-plugin");
// }
//
// public static File getAssetResource(String file) {
// return new File(getExportPath(), file);
// }
//
// public static File getBundledResource(String file) {
// final URL resource = rl.getClass().getResource(getAssetPath(file));
// if (resource == null) {
// return null;
// }
// try {
// return new File(resource.toURI());
// } catch (URISyntaxException e) {
// LOGGER.error(e);
// return new File(resource.getPath());
// }
// }
//
// public static InputStream getBundledResourceStream(String file) {
// return rl.getClass().getResourceAsStream(getAssetPath(file));
// }
//
// @NotNull
// private static String getAssetPath(String file) {
// return String.format("/assets/%s", file);
// }
//
// }
// Path: src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/icons/materialicons/MaterialIconsController.java
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.ide.BrowserUtil;
import de.mprengemann.intellij.plugin.androidicons.model.IconPack;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import de.mprengemann.intellij.plugin.androidicons.resources.ResourceLoader;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
}
@Override
public List<ImageAsset> getAssets(List<String> categories) {
return iconPack.getAssets();
}
@Override
public List<String> getCategories() {
return iconPack.getCategories();
}
@Override
public void openHelp() {
BrowserUtil.browse(iconPack.getUrl());
}
@Override
public File getImageFile(ImageAsset asset, String color, Resolution resolution) {
return getImageFile(asset, color, "24dp", resolution);
}
@Override
public File getImageFile(ImageAsset asset, String color, String size, Resolution resolution) {
final String localPath;
if (resolution == Resolution.ANYDPI) {
localPath = getVectorFilePath(asset);
} else {
localPath = getImageFilePath(asset, color, size, resolution);
} | return ResourceLoader.getAssetResource(new File(iconPack.getPath(), localPath).getPath()); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestPressureFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
// public class Pressure {
// private BigDecimal hectopascals;
// private BigDecimal millibars;
// private BigDecimal kilopascals;
// private BigDecimal inchesOfMercury;
// private BigDecimal millimetresOfMercury;
//
// public Pressure(BigDecimal hectopascals) {
// this.hectopascals = hectopascals;
// this.millibars = hectopascals;
// this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
// this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
// this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
// }
//
// public BigDecimal getValue(PressureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case HECTOPASCALS:
// value = hectopascals;
// break;
// case MILLIBARS:
// value = millibars;
// break;
// case KILIOPASCALS:
// value = kilopascals;
// break;
// case INCHES_OF_MERCURY:
// value = inchesOfMercury;
// break;
// case MILLIMETRES_OF_MERCURY:
// value = millimetresOfMercury;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Pressure;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestPressureFormatter {
private PressureFormatter testee;
@Test
public void GIVEN_null_pressure_WHEN_hectopascals_formatting_requested_THEN_returns_blank_hectopascals_value() {
testee = new PressureFormatter(null); | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
// public class Pressure {
// private BigDecimal hectopascals;
// private BigDecimal millibars;
// private BigDecimal kilopascals;
// private BigDecimal inchesOfMercury;
// private BigDecimal millimetresOfMercury;
//
// public Pressure(BigDecimal hectopascals) {
// this.hectopascals = hectopascals;
// this.millibars = hectopascals;
// this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
// this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
// this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
// }
//
// public BigDecimal getValue(PressureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case HECTOPASCALS:
// value = hectopascals;
// break;
// case MILLIBARS:
// value = millibars;
// break;
// case KILIOPASCALS:
// value = kilopascals;
// break;
// case INCHES_OF_MERCURY:
// value = inchesOfMercury;
// break;
// case MILLIMETRES_OF_MERCURY:
// value = millimetresOfMercury;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestPressureFormatter.java
import com.waynedgrant.cirrus.measures.Pressure;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestPressureFormatter {
private PressureFormatter testee;
@Test
public void GIVEN_null_pressure_WHEN_hectopascals_formatting_requested_THEN_returns_blank_hectopascals_value() {
testee = new PressureFormatter(null); | assertEquals("----.- hPa", testee.format(PressureUnit.HECTOPASCALS)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestPressureFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
// public class Pressure {
// private BigDecimal hectopascals;
// private BigDecimal millibars;
// private BigDecimal kilopascals;
// private BigDecimal inchesOfMercury;
// private BigDecimal millimetresOfMercury;
//
// public Pressure(BigDecimal hectopascals) {
// this.hectopascals = hectopascals;
// this.millibars = hectopascals;
// this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
// this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
// this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
// }
//
// public BigDecimal getValue(PressureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case HECTOPASCALS:
// value = hectopascals;
// break;
// case MILLIBARS:
// value = millibars;
// break;
// case KILIOPASCALS:
// value = kilopascals;
// break;
// case INCHES_OF_MERCURY:
// value = inchesOfMercury;
// break;
// case MILLIMETRES_OF_MERCURY:
// value = millimetresOfMercury;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Pressure;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestPressureFormatter {
private PressureFormatter testee;
@Test
public void GIVEN_null_pressure_WHEN_hectopascals_formatting_requested_THEN_returns_blank_hectopascals_value() {
testee = new PressureFormatter(null);
assertEquals("----.- hPa", testee.format(PressureUnit.HECTOPASCALS));
}
@Test
public void GIVEN_null_pressure_WHEN_millibars_formatting_requested_THEN_returns_blank_millibars_value() {
testee = new PressureFormatter(null);
assertEquals("----.- mb", testee.format(PressureUnit.MILLIBARS));
}
@Test
public void GIVEN_null_pressure_WHEN_kilopascals_formatting_requested_THEN_returns_blank_kilopascals_value() {
testee = new PressureFormatter(null);
assertEquals("---.-- kPa", testee.format(PressureUnit.KILIOPASCALS));
}
@Test
public void GIVEN_null_pressure_WHEN_inches_of_mercury_formatting_requested_THEN_returns_blank_inches_of_mercury_value() {
testee = new PressureFormatter(null);
assertEquals("--.-- inHg", testee.format(PressureUnit.INCHES_OF_MERCURY));
}
@Test
public void GIVEN_null_pressure_WHEN_millimetres_of_mercury_formatting_requested_THEN_returns_blank_millimetres_of_mercury_value() {
testee = new PressureFormatter(null);
assertEquals("---.- mmHg", testee.format(PressureUnit.MILLIMETRES_OF_MERCURY));
}
@Test
public void GIVEN_non_null_pressure_WHEN_hectopascals_formatting_requested_THEN_returns_hectopascals_value_to_one_digit() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
// public class Pressure {
// private BigDecimal hectopascals;
// private BigDecimal millibars;
// private BigDecimal kilopascals;
// private BigDecimal inchesOfMercury;
// private BigDecimal millimetresOfMercury;
//
// public Pressure(BigDecimal hectopascals) {
// this.hectopascals = hectopascals;
// this.millibars = hectopascals;
// this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
// this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
// this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
// }
//
// public BigDecimal getValue(PressureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case HECTOPASCALS:
// value = hectopascals;
// break;
// case MILLIBARS:
// value = millibars;
// break;
// case KILIOPASCALS:
// value = kilopascals;
// break;
// case INCHES_OF_MERCURY:
// value = inchesOfMercury;
// break;
// case MILLIMETRES_OF_MERCURY:
// value = millimetresOfMercury;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestPressureFormatter.java
import com.waynedgrant.cirrus.measures.Pressure;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestPressureFormatter {
private PressureFormatter testee;
@Test
public void GIVEN_null_pressure_WHEN_hectopascals_formatting_requested_THEN_returns_blank_hectopascals_value() {
testee = new PressureFormatter(null);
assertEquals("----.- hPa", testee.format(PressureUnit.HECTOPASCALS));
}
@Test
public void GIVEN_null_pressure_WHEN_millibars_formatting_requested_THEN_returns_blank_millibars_value() {
testee = new PressureFormatter(null);
assertEquals("----.- mb", testee.format(PressureUnit.MILLIBARS));
}
@Test
public void GIVEN_null_pressure_WHEN_kilopascals_formatting_requested_THEN_returns_blank_kilopascals_value() {
testee = new PressureFormatter(null);
assertEquals("---.-- kPa", testee.format(PressureUnit.KILIOPASCALS));
}
@Test
public void GIVEN_null_pressure_WHEN_inches_of_mercury_formatting_requested_THEN_returns_blank_inches_of_mercury_value() {
testee = new PressureFormatter(null);
assertEquals("--.-- inHg", testee.format(PressureUnit.INCHES_OF_MERCURY));
}
@Test
public void GIVEN_null_pressure_WHEN_millimetres_of_mercury_formatting_requested_THEN_returns_blank_millimetres_of_mercury_value() {
testee = new PressureFormatter(null);
assertEquals("---.- mmHg", testee.format(PressureUnit.MILLIMETRES_OF_MERCURY));
}
@Test
public void GIVEN_non_null_pressure_WHEN_hectopascals_formatting_requested_THEN_returns_hectopascals_value_to_one_digit() { | testee = new PressureFormatter(new Pressure(new BigDecimal("1015.66"))); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestWindSpeed.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
| package com.waynedgrant.cirrus.measures;
public class TestWindSpeed {
private WindSpeed testee;
@Test
public void GIVEN_populated_with_knots_WHEN_knots_requested_THEN_returns_correct_value() {
testee = new WindSpeed(new BigDecimal("1.5"));
| // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestWindSpeed.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.measures;
public class TestWindSpeed {
private WindSpeed testee;
@Test
public void GIVEN_populated_with_knots_WHEN_knots_requested_THEN_returns_correct_value() {
testee = new WindSpeed(new BigDecimal("1.5"));
| new BigDecimalEquals().assertEquals(new BigDecimal("1.5"), testee.getValue(WindSpeedUnit.KNOTS));
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestWindSpeed.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
| package com.waynedgrant.cirrus.measures;
public class TestWindSpeed {
private WindSpeed testee;
@Test
public void GIVEN_populated_with_knots_WHEN_knots_requested_THEN_returns_correct_value() {
testee = new WindSpeed(new BigDecimal("1.5"));
| // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestWindSpeed.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.measures;
public class TestWindSpeed {
private WindSpeed testee;
@Test
public void GIVEN_populated_with_knots_WHEN_knots_requested_THEN_returns_correct_value() {
testee = new WindSpeed(new BigDecimal("1.5"));
| new BigDecimalEquals().assertEquals(new BigDecimal("1.5"), testee.getValue(WindSpeedUnit.KNOTS));
|
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java | // Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.units.TemperatureUnit;
import java.math.BigDecimal;
| /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class Temperature {
private BigDecimal celsius;
private BigDecimal fahrenheit;
public Temperature(BigDecimal celsius) {
this.celsius = celsius;
this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
import com.waynedgrant.cirrus.units.TemperatureUnit;
import java.math.BigDecimal;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class Temperature {
private BigDecimal celsius;
private BigDecimal fahrenheit;
public Temperature(BigDecimal celsius) {
this.celsius = celsius;
this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
}
| public BigDecimal getValue(TemperatureUnit unit) {
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestPressure.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal; | package com.waynedgrant.cirrus.measures;
public class TestPressure {
private Pressure testee;
@Test
public void GIVEN_populated_with_hectopascals_WHEN_hectopascals_requested_THEN_returns_correct_value() {
testee = new Pressure(new BigDecimal("1017.7")); | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestPressure.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.measures;
public class TestPressure {
private Pressure testee;
@Test
public void GIVEN_populated_with_hectopascals_WHEN_hectopascals_requested_THEN_returns_correct_value() {
testee = new Pressure(new BigDecimal("1017.7")); | new BigDecimalEquals().assertEquals(new BigDecimal("1017.7"), testee.getValue(PressureUnit.HECTOPASCALS)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestPressure.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal; | package com.waynedgrant.cirrus.measures;
public class TestPressure {
private Pressure testee;
@Test
public void GIVEN_populated_with_hectopascals_WHEN_hectopascals_requested_THEN_returns_correct_value() {
testee = new Pressure(new BigDecimal("1017.7")); | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestPressure.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.PressureUnit;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.measures;
public class TestPressure {
private Pressure testee;
@Test
public void GIVEN_populated_with_hectopascals_WHEN_hectopascals_requested_THEN_returns_correct_value() {
testee = new Pressure(new BigDecimal("1017.7")); | new BigDecimalEquals().assertEquals(new BigDecimal("1017.7"), testee.getValue(PressureUnit.HECTOPASCALS)); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/WindDirectionFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
// public class WindDirection {
// private Integer compassDegrees;
// private CardinalDirection cardinalDirection;
//
// public WindDirection(Integer degrees) {
// this.compassDegrees = degrees;
// this.cardinalDirection = CardinalDirection.values()[(int) (((degrees + 11) / 22.5) % 16)];
// }
//
// public Integer getCompassDegrees() {
// return compassDegrees;
// }
//
// public CardinalDirection getCardinalDirection() {
// return cardinalDirection;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindDirectionUnit.java
// public enum WindDirectionUnit {
// CARDINAL_DIRECTION("Cardinal Direction"),
// COMPASS_DEGREES("Compass Degrees");
//
// private String description;
//
// WindDirectionUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import java.util.Locale;
import static com.waynedgrant.cirrus.units.WindDirectionUnit.COMPASS_DEGREES;
import com.waynedgrant.cirrus.measures.WindDirection;
import com.waynedgrant.cirrus.units.WindDirectionUnit; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class WindDirectionFormatter {
private WindDirection windDirection;
public WindDirectionFormatter(WindDirection windDirection) {
this.windDirection = windDirection;
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
// public class WindDirection {
// private Integer compassDegrees;
// private CardinalDirection cardinalDirection;
//
// public WindDirection(Integer degrees) {
// this.compassDegrees = degrees;
// this.cardinalDirection = CardinalDirection.values()[(int) (((degrees + 11) / 22.5) % 16)];
// }
//
// public Integer getCompassDegrees() {
// return compassDegrees;
// }
//
// public CardinalDirection getCardinalDirection() {
// return cardinalDirection;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindDirectionUnit.java
// public enum WindDirectionUnit {
// CARDINAL_DIRECTION("Cardinal Direction"),
// COMPASS_DEGREES("Compass Degrees");
//
// private String description;
//
// WindDirectionUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/WindDirectionFormatter.java
import java.util.Locale;
import static com.waynedgrant.cirrus.units.WindDirectionUnit.COMPASS_DEGREES;
import com.waynedgrant.cirrus.measures.WindDirection;
import com.waynedgrant.cirrus.units.WindDirectionUnit;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class WindDirectionFormatter {
private WindDirection windDirection;
public WindDirectionFormatter(WindDirection windDirection) {
this.windDirection = windDirection;
}
| public String format(WindDirectionUnit unit) { |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindSpeedFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
// public class WindSpeed {
// private BigDecimal knots;
// private BigDecimal metresPerSecond;
// private BigDecimal kilometresPerHour;
// private BigDecimal milesPerHour;
// private BigDecimal beaufortScale;
//
// public WindSpeed(BigDecimal knots) {
// this.knots = knots;
// this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
// this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
// this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
// this.beaufortScale = convertKnotsToBeaufortScale(knots);
// }
//
// public BigDecimal getValue(WindSpeedUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case KNOTS:
// value = knots;
// break;
// case METRES_PER_SECOND:
// value = metresPerSecond;
// break;
// case KILOMETRES_PER_HOUR:
// value = kilometresPerHour;
// break;
// case MILES_PER_HOUR:
// value = milesPerHour;
// break;
// case BEAUFORT_SCALE:
// value = beaufortScale;
// break;
// }
//
// return value;
// }
//
// @SuppressWarnings("ConstantConditions")
// private BigDecimal convertKnotsToBeaufortScale(BigDecimal knots) {
// int roundedKnots = knots.setScale(0, RoundingMode.HALF_UP).intValue();
//
// int beaufortScale = 0;
//
// if (roundedKnots >= 1 && roundedKnots <= 3) {
// beaufortScale = 1;
// } else if (roundedKnots >= 4 && roundedKnots <= 6) {
// beaufortScale = 2;
// } else if (roundedKnots >= 7 && roundedKnots <= 10) {
// beaufortScale = 3;
// } else if (roundedKnots >= 11 && roundedKnots <= 16) {
// beaufortScale = 4;
// } else if (roundedKnots >= 17 && roundedKnots <= 21) {
// beaufortScale = 5;
// } else if (roundedKnots >= 22 && roundedKnots <= 27) {
// beaufortScale = 6;
// } else if (roundedKnots >= 28 && roundedKnots <= 33) {
// beaufortScale = 7;
// } else if (roundedKnots >= 34 && roundedKnots <= 40) {
// beaufortScale = 8;
// } else if (roundedKnots >= 41 && roundedKnots <= 47) {
// beaufortScale = 9;
// } else if (roundedKnots >= 48 && roundedKnots <= 55) {
// beaufortScale = 10;
// } else if (roundedKnots >= 56 && roundedKnots <= 63) {
// beaufortScale = 11;
// } else if (roundedKnots >= 64) {
// beaufortScale = 12;
// }
//
// return new BigDecimal(beaufortScale);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.WindSpeed;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindSpeedFormatter {
private WindSpeedFormatter testee;
@Test
public void GIVEN_null_wind_speed_WHEN_knots_formatting_requested_THEN_returns_blank_knots_value() {
testee = new WindSpeedFormatter(null); | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
// public class WindSpeed {
// private BigDecimal knots;
// private BigDecimal metresPerSecond;
// private BigDecimal kilometresPerHour;
// private BigDecimal milesPerHour;
// private BigDecimal beaufortScale;
//
// public WindSpeed(BigDecimal knots) {
// this.knots = knots;
// this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
// this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
// this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
// this.beaufortScale = convertKnotsToBeaufortScale(knots);
// }
//
// public BigDecimal getValue(WindSpeedUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case KNOTS:
// value = knots;
// break;
// case METRES_PER_SECOND:
// value = metresPerSecond;
// break;
// case KILOMETRES_PER_HOUR:
// value = kilometresPerHour;
// break;
// case MILES_PER_HOUR:
// value = milesPerHour;
// break;
// case BEAUFORT_SCALE:
// value = beaufortScale;
// break;
// }
//
// return value;
// }
//
// @SuppressWarnings("ConstantConditions")
// private BigDecimal convertKnotsToBeaufortScale(BigDecimal knots) {
// int roundedKnots = knots.setScale(0, RoundingMode.HALF_UP).intValue();
//
// int beaufortScale = 0;
//
// if (roundedKnots >= 1 && roundedKnots <= 3) {
// beaufortScale = 1;
// } else if (roundedKnots >= 4 && roundedKnots <= 6) {
// beaufortScale = 2;
// } else if (roundedKnots >= 7 && roundedKnots <= 10) {
// beaufortScale = 3;
// } else if (roundedKnots >= 11 && roundedKnots <= 16) {
// beaufortScale = 4;
// } else if (roundedKnots >= 17 && roundedKnots <= 21) {
// beaufortScale = 5;
// } else if (roundedKnots >= 22 && roundedKnots <= 27) {
// beaufortScale = 6;
// } else if (roundedKnots >= 28 && roundedKnots <= 33) {
// beaufortScale = 7;
// } else if (roundedKnots >= 34 && roundedKnots <= 40) {
// beaufortScale = 8;
// } else if (roundedKnots >= 41 && roundedKnots <= 47) {
// beaufortScale = 9;
// } else if (roundedKnots >= 48 && roundedKnots <= 55) {
// beaufortScale = 10;
// } else if (roundedKnots >= 56 && roundedKnots <= 63) {
// beaufortScale = 11;
// } else if (roundedKnots >= 64) {
// beaufortScale = 12;
// }
//
// return new BigDecimal(beaufortScale);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindSpeedFormatter.java
import com.waynedgrant.cirrus.measures.WindSpeed;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindSpeedFormatter {
private WindSpeedFormatter testee;
@Test
public void GIVEN_null_wind_speed_WHEN_knots_formatting_requested_THEN_returns_blank_knots_value() {
testee = new WindSpeedFormatter(null); | assertEquals("--.- kts", testee.format(WindSpeedUnit.KNOTS)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindSpeedFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
// public class WindSpeed {
// private BigDecimal knots;
// private BigDecimal metresPerSecond;
// private BigDecimal kilometresPerHour;
// private BigDecimal milesPerHour;
// private BigDecimal beaufortScale;
//
// public WindSpeed(BigDecimal knots) {
// this.knots = knots;
// this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
// this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
// this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
// this.beaufortScale = convertKnotsToBeaufortScale(knots);
// }
//
// public BigDecimal getValue(WindSpeedUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case KNOTS:
// value = knots;
// break;
// case METRES_PER_SECOND:
// value = metresPerSecond;
// break;
// case KILOMETRES_PER_HOUR:
// value = kilometresPerHour;
// break;
// case MILES_PER_HOUR:
// value = milesPerHour;
// break;
// case BEAUFORT_SCALE:
// value = beaufortScale;
// break;
// }
//
// return value;
// }
//
// @SuppressWarnings("ConstantConditions")
// private BigDecimal convertKnotsToBeaufortScale(BigDecimal knots) {
// int roundedKnots = knots.setScale(0, RoundingMode.HALF_UP).intValue();
//
// int beaufortScale = 0;
//
// if (roundedKnots >= 1 && roundedKnots <= 3) {
// beaufortScale = 1;
// } else if (roundedKnots >= 4 && roundedKnots <= 6) {
// beaufortScale = 2;
// } else if (roundedKnots >= 7 && roundedKnots <= 10) {
// beaufortScale = 3;
// } else if (roundedKnots >= 11 && roundedKnots <= 16) {
// beaufortScale = 4;
// } else if (roundedKnots >= 17 && roundedKnots <= 21) {
// beaufortScale = 5;
// } else if (roundedKnots >= 22 && roundedKnots <= 27) {
// beaufortScale = 6;
// } else if (roundedKnots >= 28 && roundedKnots <= 33) {
// beaufortScale = 7;
// } else if (roundedKnots >= 34 && roundedKnots <= 40) {
// beaufortScale = 8;
// } else if (roundedKnots >= 41 && roundedKnots <= 47) {
// beaufortScale = 9;
// } else if (roundedKnots >= 48 && roundedKnots <= 55) {
// beaufortScale = 10;
// } else if (roundedKnots >= 56 && roundedKnots <= 63) {
// beaufortScale = 11;
// } else if (roundedKnots >= 64) {
// beaufortScale = 12;
// }
//
// return new BigDecimal(beaufortScale);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.WindSpeed;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindSpeedFormatter {
private WindSpeedFormatter testee;
@Test
public void GIVEN_null_wind_speed_WHEN_knots_formatting_requested_THEN_returns_blank_knots_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- kts", testee.format(WindSpeedUnit.KNOTS));
}
@Test
public void GIVEN_null_wind_speed_WHEN_metres_per_second_formatting_requested_THEN_returns_blank_metres_per_second_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- m/s", testee.format(WindSpeedUnit.METRES_PER_SECOND));
}
@Test
public void GIVEN_null_wind_speed_WHEN_kilometres_per_hour_formatting_requested_THEN_returns_blank_kilometres_per_hour_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- km/h", testee.format(WindSpeedUnit.KILOMETRES_PER_HOUR));
}
@Test
public void GIVEN_null_wind_speed_WHEN_miles_per_hour_formatting_requested_THEN_returns_blank_miles_per_hour_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- mph", testee.format(WindSpeedUnit.MILES_PER_HOUR));
}
@Test
public void GIVEN_null_wind_speed_WHEN_beaufort_scale_formatting_requested_THEN_returns_blank_beaufort_scale_value() {
testee = new WindSpeedFormatter(null);
assertEquals("-- Bft", testee.format(WindSpeedUnit.BEAUFORT_SCALE));
}
@Test
public void GIVEN_non_null_wind_speed_WHEN_knots_formatting_requested_THEN_returns_knots_value_to_one_digit() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
// public class WindSpeed {
// private BigDecimal knots;
// private BigDecimal metresPerSecond;
// private BigDecimal kilometresPerHour;
// private BigDecimal milesPerHour;
// private BigDecimal beaufortScale;
//
// public WindSpeed(BigDecimal knots) {
// this.knots = knots;
// this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
// this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
// this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
// this.beaufortScale = convertKnotsToBeaufortScale(knots);
// }
//
// public BigDecimal getValue(WindSpeedUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case KNOTS:
// value = knots;
// break;
// case METRES_PER_SECOND:
// value = metresPerSecond;
// break;
// case KILOMETRES_PER_HOUR:
// value = kilometresPerHour;
// break;
// case MILES_PER_HOUR:
// value = milesPerHour;
// break;
// case BEAUFORT_SCALE:
// value = beaufortScale;
// break;
// }
//
// return value;
// }
//
// @SuppressWarnings("ConstantConditions")
// private BigDecimal convertKnotsToBeaufortScale(BigDecimal knots) {
// int roundedKnots = knots.setScale(0, RoundingMode.HALF_UP).intValue();
//
// int beaufortScale = 0;
//
// if (roundedKnots >= 1 && roundedKnots <= 3) {
// beaufortScale = 1;
// } else if (roundedKnots >= 4 && roundedKnots <= 6) {
// beaufortScale = 2;
// } else if (roundedKnots >= 7 && roundedKnots <= 10) {
// beaufortScale = 3;
// } else if (roundedKnots >= 11 && roundedKnots <= 16) {
// beaufortScale = 4;
// } else if (roundedKnots >= 17 && roundedKnots <= 21) {
// beaufortScale = 5;
// } else if (roundedKnots >= 22 && roundedKnots <= 27) {
// beaufortScale = 6;
// } else if (roundedKnots >= 28 && roundedKnots <= 33) {
// beaufortScale = 7;
// } else if (roundedKnots >= 34 && roundedKnots <= 40) {
// beaufortScale = 8;
// } else if (roundedKnots >= 41 && roundedKnots <= 47) {
// beaufortScale = 9;
// } else if (roundedKnots >= 48 && roundedKnots <= 55) {
// beaufortScale = 10;
// } else if (roundedKnots >= 56 && roundedKnots <= 63) {
// beaufortScale = 11;
// } else if (roundedKnots >= 64) {
// beaufortScale = 12;
// }
//
// return new BigDecimal(beaufortScale);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindSpeedFormatter.java
import com.waynedgrant.cirrus.measures.WindSpeed;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindSpeedFormatter {
private WindSpeedFormatter testee;
@Test
public void GIVEN_null_wind_speed_WHEN_knots_formatting_requested_THEN_returns_blank_knots_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- kts", testee.format(WindSpeedUnit.KNOTS));
}
@Test
public void GIVEN_null_wind_speed_WHEN_metres_per_second_formatting_requested_THEN_returns_blank_metres_per_second_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- m/s", testee.format(WindSpeedUnit.METRES_PER_SECOND));
}
@Test
public void GIVEN_null_wind_speed_WHEN_kilometres_per_hour_formatting_requested_THEN_returns_blank_kilometres_per_hour_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- km/h", testee.format(WindSpeedUnit.KILOMETRES_PER_HOUR));
}
@Test
public void GIVEN_null_wind_speed_WHEN_miles_per_hour_formatting_requested_THEN_returns_blank_miles_per_hour_value() {
testee = new WindSpeedFormatter(null);
assertEquals("--.- mph", testee.format(WindSpeedUnit.MILES_PER_HOUR));
}
@Test
public void GIVEN_null_wind_speed_WHEN_beaufort_scale_formatting_requested_THEN_returns_blank_beaufort_scale_value() {
testee = new WindSpeedFormatter(null);
assertEquals("-- Bft", testee.format(WindSpeedUnit.BEAUFORT_SCALE));
}
@Test
public void GIVEN_non_null_wind_speed_WHEN_knots_formatting_requested_THEN_returns_knots_value_to_one_digit() { | testee = new WindSpeedFormatter(new WindSpeed(new BigDecimal("15.66"))); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/TemperatureFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.TemperatureUnit.CELSIUS; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class TemperatureFormatter {
private Temperature temperature;
public TemperatureFormatter(Temperature temperature) {
this.temperature = temperature;
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/TemperatureFormatter.java
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.TemperatureUnit.CELSIUS;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class TemperatureFormatter {
private Temperature temperature;
public TemperatureFormatter(Temperature temperature) {
this.temperature = temperature;
}
| public String format(TemperatureUnit unit) { |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestTemperature.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
| package com.waynedgrant.cirrus.measures;
public class TestTemperature {
private Temperature testee;
@Test
public void GIVEN_populated_with_celsius_WHEN_celsius_requested_THEN_returns_correct_value() {
testee = new Temperature(new BigDecimal("25.5"));
| // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestTemperature.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.measures;
public class TestTemperature {
private Temperature testee;
@Test
public void GIVEN_populated_with_celsius_WHEN_celsius_requested_THEN_returns_correct_value() {
testee = new Temperature(new BigDecimal("25.5"));
| assertEquals(new BigDecimal("25.5"), testee.getValue(TemperatureUnit.CELSIUS));
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestTemperature.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
| package com.waynedgrant.cirrus.measures;
public class TestTemperature {
private Temperature testee;
@Test
public void GIVEN_populated_with_celsius_WHEN_celsius_requested_THEN_returns_correct_value() {
testee = new Temperature(new BigDecimal("25.5"));
assertEquals(new BigDecimal("25.5"), testee.getValue(TemperatureUnit.CELSIUS));
}
@Test
public void GIVEN_populated_with_celsius_WHEN_fahrenheit_requested_THEN_returns_correct_value() {
testee = new Temperature(new BigDecimal("-50.5"));
| // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestTemperature.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.measures;
public class TestTemperature {
private Temperature testee;
@Test
public void GIVEN_populated_with_celsius_WHEN_celsius_requested_THEN_returns_correct_value() {
testee = new Temperature(new BigDecimal("25.5"));
assertEquals(new BigDecimal("25.5"), testee.getValue(TemperatureUnit.CELSIUS));
}
@Test
public void GIVEN_populated_with_celsius_WHEN_fahrenheit_requested_THEN_returns_correct_value() {
testee = new Temperature(new BigDecimal("-50.5"));
| new BigDecimalEquals().assertEquals(new BigDecimal("-58.9"), testee.getValue(TemperatureUnit.FAHRENHEIT));
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestConditionsFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Conditions.java
// public enum Conditions {
// SUNNY_1(0, "Sunny"),
// CLEAR_NIGHT(1, "Clear Night"),
// CLOUDY_1(2, "Cloudy"),
// CLOUDY_2(3, "Cloudy"),
// CLOUDY_NIGHT(4, "Cloudy Night"),
// DRY_CLEAR(5, "Dry Clear"),
// FOG(6, "Fog"),
// HAZY(7, "Hazy"),
// HEAVY_RAIN(8, "Heavy Rain"),
// MAINLY_FINE(9, "Mainly Fine"),
// MISTY(10, "Misty"),
// NIGHT_FOG(11, "Night Fog"),
// NIGHT_HEAVY_RAIN(12, "Night Heavy Rain"),
// NIGHT_OVERCAST(13, "Night Overcast"),
// NIGHT_RAIN(14, "Night Rain"),
// NIGHT_SHOWERS(15, "Night Showers"),
// NIGHT_SNOW(16, "Night Snow"),
// NIGHT_THUNDER(17, "Night Thunder"),
// OVERCAST(18, "Overcast"),
// PARTLY_CLOUDY(19, "Partly Cloudy"),
// RAIN(20, "Rain"),
// HARD_RAIN(21, "Hard Rain"),
// SHOWERS(22, "Showers"),
// SLEET(23, "Sleet"),
// SLEET_SHOWERS(24, "Sleet Showers"),
// SNOWING(25, "Snow"),
// SNOW_MELT(26, "Snow Melt"),
// SNOW_SHOWERS(27, "Snow Showers"),
// SUNNY_2(28, "Sunny"),
// THUNDER_SHOWERS_1(29, "Thunder Showers"),
// THUNDER_SHOWERS_2(30, "Thunder Showers"),
// THUNDERSTORMS(31, "Thunderstorms"),
// TORNADO_WARNING(32, "Tornado Warning"),
// WINDY(33, "Windy"),
// STOPPED_RAINING(34, "Stopped Raining"),
// WINDY_RAIN(35, "Windy Rain");
//
// private int icon;
// private String description;
//
// Conditions(int icon, String description) {
// this.icon = icon;
// this.description = description;
// }
//
// public int getIcon() {
// return icon;
// }
//
// public String getDescription() {
// return description;
// }
//
// public static Conditions resolveIcon(int icon) {
// Conditions resolved = null;
//
// for (Conditions conditions : Conditions.values()) {
// if (conditions.icon == icon) {
// resolved = conditions;
// break;
// }
// }
//
// return resolved;
// }
// }
| import com.waynedgrant.cirrus.measures.Conditions;
import org.junit.Test;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestConditionsFormatter {
private ConditionsFormatter testee;
@Test
public void GIVEN_null_conditions_WHEN_formatting_requested_THEN_returns_blank_value() {
testee = new ConditionsFormatter(null);
assertEquals("-", testee.format());
}
@Test
public void GIVEN_conditions_WHEN_formatting_requested_THEN_returns_conditions_description() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Conditions.java
// public enum Conditions {
// SUNNY_1(0, "Sunny"),
// CLEAR_NIGHT(1, "Clear Night"),
// CLOUDY_1(2, "Cloudy"),
// CLOUDY_2(3, "Cloudy"),
// CLOUDY_NIGHT(4, "Cloudy Night"),
// DRY_CLEAR(5, "Dry Clear"),
// FOG(6, "Fog"),
// HAZY(7, "Hazy"),
// HEAVY_RAIN(8, "Heavy Rain"),
// MAINLY_FINE(9, "Mainly Fine"),
// MISTY(10, "Misty"),
// NIGHT_FOG(11, "Night Fog"),
// NIGHT_HEAVY_RAIN(12, "Night Heavy Rain"),
// NIGHT_OVERCAST(13, "Night Overcast"),
// NIGHT_RAIN(14, "Night Rain"),
// NIGHT_SHOWERS(15, "Night Showers"),
// NIGHT_SNOW(16, "Night Snow"),
// NIGHT_THUNDER(17, "Night Thunder"),
// OVERCAST(18, "Overcast"),
// PARTLY_CLOUDY(19, "Partly Cloudy"),
// RAIN(20, "Rain"),
// HARD_RAIN(21, "Hard Rain"),
// SHOWERS(22, "Showers"),
// SLEET(23, "Sleet"),
// SLEET_SHOWERS(24, "Sleet Showers"),
// SNOWING(25, "Snow"),
// SNOW_MELT(26, "Snow Melt"),
// SNOW_SHOWERS(27, "Snow Showers"),
// SUNNY_2(28, "Sunny"),
// THUNDER_SHOWERS_1(29, "Thunder Showers"),
// THUNDER_SHOWERS_2(30, "Thunder Showers"),
// THUNDERSTORMS(31, "Thunderstorms"),
// TORNADO_WARNING(32, "Tornado Warning"),
// WINDY(33, "Windy"),
// STOPPED_RAINING(34, "Stopped Raining"),
// WINDY_RAIN(35, "Windy Rain");
//
// private int icon;
// private String description;
//
// Conditions(int icon, String description) {
// this.icon = icon;
// this.description = description;
// }
//
// public int getIcon() {
// return icon;
// }
//
// public String getDescription() {
// return description;
// }
//
// public static Conditions resolveIcon(int icon) {
// Conditions resolved = null;
//
// for (Conditions conditions : Conditions.values()) {
// if (conditions.icon == icon) {
// resolved = conditions;
// break;
// }
// }
//
// return resolved;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestConditionsFormatter.java
import com.waynedgrant.cirrus.measures.Conditions;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestConditionsFormatter {
private ConditionsFormatter testee;
@Test
public void GIVEN_null_conditions_WHEN_formatting_requested_THEN_returns_blank_value() {
testee = new ConditionsFormatter(null);
assertEquals("-", testee.format());
}
@Test
public void GIVEN_conditions_WHEN_formatting_requested_THEN_returns_conditions_description() { | testee = new ConditionsFormatter(Conditions.CLEAR_NIGHT); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java | // Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import static java.math.MathContext.DECIMAL32;
import com.waynedgrant.cirrus.units.PressureUnit;
import java.math.BigDecimal;
| /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class Pressure {
private BigDecimal hectopascals;
private BigDecimal millibars;
private BigDecimal kilopascals;
private BigDecimal inchesOfMercury;
private BigDecimal millimetresOfMercury;
public Pressure(BigDecimal hectopascals) {
this.hectopascals = hectopascals;
this.millibars = hectopascals;
this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
import static java.math.MathContext.DECIMAL32;
import com.waynedgrant.cirrus.units.PressureUnit;
import java.math.BigDecimal;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class Pressure {
private BigDecimal hectopascals;
private BigDecimal millibars;
private BigDecimal kilopascals;
private BigDecimal inchesOfMercury;
private BigDecimal millimetresOfMercury;
public Pressure(BigDecimal hectopascals) {
this.hectopascals = hectopascals;
this.millibars = hectopascals;
this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
}
| public BigDecimal getValue(PressureUnit unit) {
|
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/PressureFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
// public class Pressure {
// private BigDecimal hectopascals;
// private BigDecimal millibars;
// private BigDecimal kilopascals;
// private BigDecimal inchesOfMercury;
// private BigDecimal millimetresOfMercury;
//
// public Pressure(BigDecimal hectopascals) {
// this.hectopascals = hectopascals;
// this.millibars = hectopascals;
// this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
// this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
// this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
// }
//
// public BigDecimal getValue(PressureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case HECTOPASCALS:
// value = hectopascals;
// break;
// case MILLIBARS:
// value = millibars;
// break;
// case KILIOPASCALS:
// value = kilopascals;
// break;
// case INCHES_OF_MERCURY:
// value = inchesOfMercury;
// break;
// case MILLIMETRES_OF_MERCURY:
// value = millimetresOfMercury;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Pressure;
import com.waynedgrant.cirrus.units.PressureUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.PressureUnit.HECTOPASCALS;
import static com.waynedgrant.cirrus.units.PressureUnit.INCHES_OF_MERCURY;
import static com.waynedgrant.cirrus.units.PressureUnit.KILIOPASCALS;
import static com.waynedgrant.cirrus.units.PressureUnit.MILLIBARS; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class PressureFormatter {
private Pressure pressure;
public PressureFormatter(Pressure pressure) {
this.pressure = pressure;
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Pressure.java
// public class Pressure {
// private BigDecimal hectopascals;
// private BigDecimal millibars;
// private BigDecimal kilopascals;
// private BigDecimal inchesOfMercury;
// private BigDecimal millimetresOfMercury;
//
// public Pressure(BigDecimal hectopascals) {
// this.hectopascals = hectopascals;
// this.millibars = hectopascals;
// this.kilopascals = hectopascals.divide(new BigDecimal("10"), DECIMAL32);
// this.inchesOfMercury = hectopascals.multiply(new BigDecimal("0.02953"), DECIMAL32);
// this.millimetresOfMercury = hectopascals.multiply(new BigDecimal("0.750062"), DECIMAL32);
// }
//
// public BigDecimal getValue(PressureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case HECTOPASCALS:
// value = hectopascals;
// break;
// case MILLIBARS:
// value = millibars;
// break;
// case KILIOPASCALS:
// value = kilopascals;
// break;
// case INCHES_OF_MERCURY:
// value = inchesOfMercury;
// break;
// case MILLIMETRES_OF_MERCURY:
// value = millimetresOfMercury;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/PressureUnit.java
// public enum PressureUnit {
// HECTOPASCALS("Hectopascals (hPa)"),
// INCHES_OF_MERCURY("Inches of Mercury (inHg)"),
// KILIOPASCALS("Kilopascals (kPa)"),
// MILLIBARS("Millibars (mb)"),
// MILLIMETRES_OF_MERCURY("Millimetres of Mercury (mmHg)");
//
// private String description;
//
// PressureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/PressureFormatter.java
import com.waynedgrant.cirrus.measures.Pressure;
import com.waynedgrant.cirrus.units.PressureUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.PressureUnit.HECTOPASCALS;
import static com.waynedgrant.cirrus.units.PressureUnit.INCHES_OF_MERCURY;
import static com.waynedgrant.cirrus.units.PressureUnit.KILIOPASCALS;
import static com.waynedgrant.cirrus.units.PressureUnit.MILLIBARS;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class PressureFormatter {
private Pressure pressure;
public PressureFormatter(Pressure pressure) {
this.pressure = pressure;
}
| public String format(PressureUnit unit) { |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java | // Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import java.math.RoundingMode;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import java.math.BigDecimal;
| /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class WindSpeed {
private BigDecimal knots;
private BigDecimal metresPerSecond;
private BigDecimal kilometresPerHour;
private BigDecimal milesPerHour;
private BigDecimal beaufortScale;
public WindSpeed(BigDecimal knots) {
this.knots = knots;
this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
this.beaufortScale = convertKnotsToBeaufortScale(knots);
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
import java.math.RoundingMode;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import java.math.BigDecimal;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class WindSpeed {
private BigDecimal knots;
private BigDecimal metresPerSecond;
private BigDecimal kilometresPerHour;
private BigDecimal milesPerHour;
private BigDecimal beaufortScale;
public WindSpeed(BigDecimal knots) {
this.knots = knots;
this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
this.beaufortScale = convertKnotsToBeaufortScale(knots);
}
| public BigDecimal getValue(WindSpeedUnit unit) {
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallRateFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallRateFormatter {
private RainfallRateFormatter testee;
@Test
public void GIVEN_null_rainfall_rate_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallRateFormatter(null); | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallRateFormatter.java
import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallRateFormatter {
private RainfallRateFormatter testee;
@Test
public void GIVEN_null_rainfall_rate_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallRateFormatter(null); | assertEquals("-.-- mm/min", testee.format(RainfallUnit.MILLIMETRES)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallRateFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallRateFormatter {
private RainfallRateFormatter testee;
@Test
public void GIVEN_null_rainfall_rate_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallRateFormatter(null);
assertEquals("-.-- mm/min", testee.format(RainfallUnit.MILLIMETRES));
}
@Test
public void GIVEN_null_rainfall_rate_WHEN_inches_formatting_requested_THEN_returns_blank_inches_value() {
testee = new RainfallRateFormatter(null);
assertEquals("-.--- in/min", testee.format(RainfallUnit.INCHES));
}
@Test
public void GIVEN_non_null_rainfall_rate_WHEN_millmetres_formatting_requested_THEN_returns_millmetres_value_to_three_digits() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallRateFormatter.java
import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallRateFormatter {
private RainfallRateFormatter testee;
@Test
public void GIVEN_null_rainfall_rate_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallRateFormatter(null);
assertEquals("-.-- mm/min", testee.format(RainfallUnit.MILLIMETRES));
}
@Test
public void GIVEN_null_rainfall_rate_WHEN_inches_formatting_requested_THEN_returns_blank_inches_value() {
testee = new RainfallRateFormatter(null);
assertEquals("-.--- in/min", testee.format(RainfallUnit.INCHES));
}
@Test
public void GIVEN_non_null_rainfall_rate_WHEN_millmetres_formatting_requested_THEN_returns_millmetres_value_to_three_digits() { | testee = new RainfallRateFormatter(new Rainfall(new BigDecimal("5.666"))); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallFormatter {
private RainfallFormatter testee;
@Test
public void GIVEN_null_rainfall_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallFormatter(null); | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallFormatter.java
import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallFormatter {
private RainfallFormatter testee;
@Test
public void GIVEN_null_rainfall_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallFormatter(null); | assertEquals("-.-- mm", testee.format(RainfallUnit.MILLIMETRES)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallFormatter {
private RainfallFormatter testee;
@Test
public void GIVEN_null_rainfall_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallFormatter(null);
assertEquals("-.-- mm", testee.format(RainfallUnit.MILLIMETRES));
}
@Test
public void GIVEN_null_rainfall_WHEN_inches_formatting_requested_THEN_returns_blank_inches_value() {
testee = new RainfallFormatter(null);
assertEquals("-.-- in", testee.format(RainfallUnit.INCHES));
}
@Test
public void GIVEN_non_null_rainfall_WHEN_millmetres_formatting_requested_THEN_returns_millmetres_value_to_two_digits() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestRainfallFormatter.java
import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestRainfallFormatter {
private RainfallFormatter testee;
@Test
public void GIVEN_null_rainfall_WHEN_millmetres_formatting_requested_THEN_returns_blank_millmetres_value() {
testee = new RainfallFormatter(null);
assertEquals("-.-- mm", testee.format(RainfallUnit.MILLIMETRES));
}
@Test
public void GIVEN_null_rainfall_WHEN_inches_formatting_requested_THEN_returns_blank_inches_value() {
testee = new RainfallFormatter(null);
assertEquals("-.-- in", testee.format(RainfallUnit.INCHES));
}
@Test
public void GIVEN_non_null_rainfall_WHEN_millmetres_formatting_requested_THEN_returns_millmetres_value_to_two_digits() { | testee = new RainfallFormatter(new Rainfall(new BigDecimal("5.666"))); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindDirectionFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
// public class WindDirection {
// private Integer compassDegrees;
// private CardinalDirection cardinalDirection;
//
// public WindDirection(Integer degrees) {
// this.compassDegrees = degrees;
// this.cardinalDirection = CardinalDirection.values()[(int) (((degrees + 11) / 22.5) % 16)];
// }
//
// public Integer getCompassDegrees() {
// return compassDegrees;
// }
//
// public CardinalDirection getCardinalDirection() {
// return cardinalDirection;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindDirectionUnit.java
// public enum WindDirectionUnit {
// CARDINAL_DIRECTION("Cardinal Direction"),
// COMPASS_DEGREES("Compass Degrees");
//
// private String description;
//
// WindDirectionUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.WindDirection;
import com.waynedgrant.cirrus.units.WindDirectionUnit;
import org.junit.Test;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindDirectionFormatter {
private WindDirectionFormatter testee;
@Test
public void GIVEN_null_wind_direction_WHEN_compass_degrees_formatting_requested_THEN_returns_blank_compass_degrees_value() {
testee = new WindDirectionFormatter(null); | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
// public class WindDirection {
// private Integer compassDegrees;
// private CardinalDirection cardinalDirection;
//
// public WindDirection(Integer degrees) {
// this.compassDegrees = degrees;
// this.cardinalDirection = CardinalDirection.values()[(int) (((degrees + 11) / 22.5) % 16)];
// }
//
// public Integer getCompassDegrees() {
// return compassDegrees;
// }
//
// public CardinalDirection getCardinalDirection() {
// return cardinalDirection;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindDirectionUnit.java
// public enum WindDirectionUnit {
// CARDINAL_DIRECTION("Cardinal Direction"),
// COMPASS_DEGREES("Compass Degrees");
//
// private String description;
//
// WindDirectionUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindDirectionFormatter.java
import com.waynedgrant.cirrus.measures.WindDirection;
import com.waynedgrant.cirrus.units.WindDirectionUnit;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindDirectionFormatter {
private WindDirectionFormatter testee;
@Test
public void GIVEN_null_wind_direction_WHEN_compass_degrees_formatting_requested_THEN_returns_blank_compass_degrees_value() {
testee = new WindDirectionFormatter(null); | assertEquals("---°", testee.format(WindDirectionUnit.COMPASS_DEGREES)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindDirectionFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
// public class WindDirection {
// private Integer compassDegrees;
// private CardinalDirection cardinalDirection;
//
// public WindDirection(Integer degrees) {
// this.compassDegrees = degrees;
// this.cardinalDirection = CardinalDirection.values()[(int) (((degrees + 11) / 22.5) % 16)];
// }
//
// public Integer getCompassDegrees() {
// return compassDegrees;
// }
//
// public CardinalDirection getCardinalDirection() {
// return cardinalDirection;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindDirectionUnit.java
// public enum WindDirectionUnit {
// CARDINAL_DIRECTION("Cardinal Direction"),
// COMPASS_DEGREES("Compass Degrees");
//
// private String description;
//
// WindDirectionUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.WindDirection;
import com.waynedgrant.cirrus.units.WindDirectionUnit;
import org.junit.Test;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindDirectionFormatter {
private WindDirectionFormatter testee;
@Test
public void GIVEN_null_wind_direction_WHEN_compass_degrees_formatting_requested_THEN_returns_blank_compass_degrees_value() {
testee = new WindDirectionFormatter(null);
assertEquals("---°", testee.format(WindDirectionUnit.COMPASS_DEGREES));
}
@Test
public void GIVEN_null_wind_direction_WHEN_cardinal_direction_formatting_requested_THEN_returns_blank_cardinal_direction_value() {
testee = new WindDirectionFormatter(null);
assertEquals("---", testee.format(WindDirectionUnit.CARDINAL_DIRECTION));
}
@Test
public void GIVEN_non_null_wind_direction_WHEN_compass_degrees_formatting_requested_THEN_returns_compass_degrees_value() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
// public class WindDirection {
// private Integer compassDegrees;
// private CardinalDirection cardinalDirection;
//
// public WindDirection(Integer degrees) {
// this.compassDegrees = degrees;
// this.cardinalDirection = CardinalDirection.values()[(int) (((degrees + 11) / 22.5) % 16)];
// }
//
// public Integer getCompassDegrees() {
// return compassDegrees;
// }
//
// public CardinalDirection getCardinalDirection() {
// return cardinalDirection;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindDirectionUnit.java
// public enum WindDirectionUnit {
// CARDINAL_DIRECTION("Cardinal Direction"),
// COMPASS_DEGREES("Compass Degrees");
//
// private String description;
//
// WindDirectionUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestWindDirectionFormatter.java
import com.waynedgrant.cirrus.measures.WindDirection;
import com.waynedgrant.cirrus.units.WindDirectionUnit;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestWindDirectionFormatter {
private WindDirectionFormatter testee;
@Test
public void GIVEN_null_wind_direction_WHEN_compass_degrees_formatting_requested_THEN_returns_blank_compass_degrees_value() {
testee = new WindDirectionFormatter(null);
assertEquals("---°", testee.format(WindDirectionUnit.COMPASS_DEGREES));
}
@Test
public void GIVEN_null_wind_direction_WHEN_cardinal_direction_formatting_requested_THEN_returns_blank_cardinal_direction_value() {
testee = new WindDirectionFormatter(null);
assertEquals("---", testee.format(WindDirectionUnit.CARDINAL_DIRECTION));
}
@Test
public void GIVEN_non_null_wind_direction_WHEN_compass_degrees_formatting_requested_THEN_returns_compass_degrees_value() { | testee = new WindDirectionFormatter(new WindDirection(0)); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/colorizers/TemperatureColorizer.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import java.math.BigDecimal;
import java.math.RoundingMode;
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.colorizers;
public class TemperatureColorizer {
public static final int WHITE = 0xffffffff;
public static final int LIGHT_BLUE = 0xff69c3ff;
public static final int DARK_GREEN = 0xffaaffaa;
public static final int MEDIUM_GREEN = 0xffc3ff5d;
public static final int LIGHT_GREEN = 0xffdefc4e;
public static final int LIGHT_YELLOW = 0xfffff83b;
public static final int MEDIUM_YELLOW = 0xffffdc36;
public static final int DARK_YELLOW = 0xffffcd30;
public static final int LIGHT_ORANGE = 0xffffb230;
public static final int MEDIUM_ORANGE = 0xffff9b25;
public static final int DARK_ORANGE = 0xffff8700;
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/colorizers/TemperatureColorizer.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.colorizers;
public class TemperatureColorizer {
public static final int WHITE = 0xffffffff;
public static final int LIGHT_BLUE = 0xff69c3ff;
public static final int DARK_GREEN = 0xffaaffaa;
public static final int MEDIUM_GREEN = 0xffc3ff5d;
public static final int LIGHT_GREEN = 0xffdefc4e;
public static final int LIGHT_YELLOW = 0xfffff83b;
public static final int MEDIUM_YELLOW = 0xffffdc36;
public static final int DARK_YELLOW = 0xffffcd30;
public static final int LIGHT_ORANGE = 0xffffb230;
public static final int MEDIUM_ORANGE = 0xffff9b25;
public static final int DARK_ORANGE = 0xffff8700;
| private Temperature temperature; |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/colorizers/TemperatureColorizer.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import java.math.BigDecimal;
import java.math.RoundingMode;
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.colorizers;
public class TemperatureColorizer {
public static final int WHITE = 0xffffffff;
public static final int LIGHT_BLUE = 0xff69c3ff;
public static final int DARK_GREEN = 0xffaaffaa;
public static final int MEDIUM_GREEN = 0xffc3ff5d;
public static final int LIGHT_GREEN = 0xffdefc4e;
public static final int LIGHT_YELLOW = 0xfffff83b;
public static final int MEDIUM_YELLOW = 0xffffdc36;
public static final int DARK_YELLOW = 0xffffcd30;
public static final int LIGHT_ORANGE = 0xffffb230;
public static final int MEDIUM_ORANGE = 0xffff9b25;
public static final int DARK_ORANGE = 0xffff8700;
private Temperature temperature;
public TemperatureColorizer(Temperature temperature) {
this.temperature = temperature;
}
public int colorize() {
int colorCode = WHITE;
if (temperature != null) { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/colorizers/TemperatureColorizer.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.colorizers;
public class TemperatureColorizer {
public static final int WHITE = 0xffffffff;
public static final int LIGHT_BLUE = 0xff69c3ff;
public static final int DARK_GREEN = 0xffaaffaa;
public static final int MEDIUM_GREEN = 0xffc3ff5d;
public static final int LIGHT_GREEN = 0xffdefc4e;
public static final int LIGHT_YELLOW = 0xfffff83b;
public static final int MEDIUM_YELLOW = 0xffffdc36;
public static final int DARK_YELLOW = 0xffffcd30;
public static final int LIGHT_ORANGE = 0xffffb230;
public static final int MEDIUM_ORANGE = 0xffff9b25;
public static final int DARK_ORANGE = 0xffff8700;
private Temperature temperature;
public TemperatureColorizer(Temperature temperature) {
this.temperature = temperature;
}
public int colorize() {
int colorCode = WHITE;
if (temperature != null) { | BigDecimal temperatureCelsius = temperature.getValue(TemperatureUnit.CELSIUS); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestTemperatureFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestTemperatureFormatter {
private TemperatureFormatter testee;
@Test
public void GIVEN_null_temperature_WHEN_celsius_formatting_requested_THEN_returns_blank_celsius_value() {
testee = new TemperatureFormatter(null); | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestTemperatureFormatter.java
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestTemperatureFormatter {
private TemperatureFormatter testee;
@Test
public void GIVEN_null_temperature_WHEN_celsius_formatting_requested_THEN_returns_blank_celsius_value() {
testee = new TemperatureFormatter(null); | assertEquals("--.-°C", testee.format(TemperatureUnit.CELSIUS)); |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestTemperatureFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestTemperatureFormatter {
private TemperatureFormatter testee;
@Test
public void GIVEN_null_temperature_WHEN_celsius_formatting_requested_THEN_returns_blank_celsius_value() {
testee = new TemperatureFormatter(null);
assertEquals("--.-°C", testee.format(TemperatureUnit.CELSIUS));
}
@Test
public void GIVEN_null_temperature_WHEN_fahrenheit_formatting_requested_THEN_returns_blank_fahrenheit_value() {
testee = new TemperatureFormatter(null);
assertEquals("--.-°F", testee.format(TemperatureUnit.FAHRENHEIT));
}
@Test
public void GIVEN_non_null_temperature_WHEN_celsius_formatting_requested_THEN_returns_celsius_value_to_one_digit() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/TemperatureUnit.java
// public enum TemperatureUnit {
// CELSIUS("Celsius (°C)"),
// FAHRENHEIT("Fahrenheit (°F)");
//
// private String description;
//
// TemperatureUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestTemperatureFormatter.java
import com.waynedgrant.cirrus.measures.Temperature;
import com.waynedgrant.cirrus.units.TemperatureUnit;
import org.junit.Test;
import java.math.BigDecimal;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestTemperatureFormatter {
private TemperatureFormatter testee;
@Test
public void GIVEN_null_temperature_WHEN_celsius_formatting_requested_THEN_returns_blank_celsius_value() {
testee = new TemperatureFormatter(null);
assertEquals("--.-°C", testee.format(TemperatureUnit.CELSIUS));
}
@Test
public void GIVEN_null_temperature_WHEN_fahrenheit_formatting_requested_THEN_returns_blank_fahrenheit_value() {
testee = new TemperatureFormatter(null);
assertEquals("--.-°F", testee.format(TemperatureUnit.FAHRENHEIT));
}
@Test
public void GIVEN_non_null_temperature_WHEN_celsius_formatting_requested_THEN_returns_celsius_value_to_one_digit() { | testee = new TemperatureFormatter(new Temperature(new BigDecimal("-15.66"))); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java | // Path: app/src/main/java/com/waynedgrant/cirrus/units/CardinalDirection.java
// public enum CardinalDirection {
// N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW
// }
| import com.waynedgrant.cirrus.units.CardinalDirection;
| /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class WindDirection {
private Integer compassDegrees;
| // Path: app/src/main/java/com/waynedgrant/cirrus/units/CardinalDirection.java
// public enum CardinalDirection {
// N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindDirection.java
import com.waynedgrant.cirrus.units.CardinalDirection;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class WindDirection {
private Integer compassDegrees;
| private CardinalDirection cardinalDirection;
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestTrendFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Trend.java
// public enum Trend {
// RISING,
// STEADY,
// FALLING
// }
| import com.waynedgrant.cirrus.measures.Trend;
import org.junit.Test;
import static junit.framework.Assert.assertEquals; | package com.waynedgrant.cirrus.presentation.formatters;
public class TestTrendFormatter {
private TrendFormatter testee;
@Test
public void GIVEN_null_trend_WHEN_formatting_requested_THEN_returns_blank_character() {
testee = new TrendFormatter(null);
assertEquals("-", testee.format());
}
@Test
public void GIVEN_rising_trend_WHEN_formatting_requested_THEN_returns_rising_character() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Trend.java
// public enum Trend {
// RISING,
// STEADY,
// FALLING
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/formatters/TestTrendFormatter.java
import com.waynedgrant.cirrus.measures.Trend;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
package com.waynedgrant.cirrus.presentation.formatters;
public class TestTrendFormatter {
private TrendFormatter testee;
@Test
public void GIVEN_null_trend_WHEN_formatting_requested_THEN_returns_blank_character() {
testee = new TrendFormatter(null);
assertEquals("-", testee.format());
}
@Test
public void GIVEN_rising_trend_WHEN_formatting_requested_THEN_returns_rising_character() { | testee = new TrendFormatter(Trend.RISING); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/RainfallFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.RainfallUnit.MILLIMETRES; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class RainfallFormatter {
private Rainfall rainfall;
public RainfallFormatter(Rainfall rainfall) {
this.rainfall = rainfall;
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/RainfallFormatter.java
import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.RainfallUnit.MILLIMETRES;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class RainfallFormatter {
private Rainfall rainfall;
public RainfallFormatter(Rainfall rainfall) {
this.rainfall = rainfall;
}
| public String format(RainfallUnit unit) { |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestRainfall.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
| package com.waynedgrant.cirrus.measures;
public class TestRainfall {
private Rainfall testee;
@Test
public void GIVEN_populated_with_millmetres_WHEN_millimetres_requested_THEN_returns_correct_value() {
testee = new Rainfall(new BigDecimal("2.5"));
| // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestRainfall.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.measures;
public class TestRainfall {
private Rainfall testee;
@Test
public void GIVEN_populated_with_millmetres_WHEN_millimetres_requested_THEN_returns_correct_value() {
testee = new Rainfall(new BigDecimal("2.5"));
| new BigDecimalEquals().assertEquals(new BigDecimal("2.5"), testee.getValue(RainfallUnit.MILLIMETRES));
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestRainfall.java | // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
| package com.waynedgrant.cirrus.measures;
public class TestRainfall {
private Rainfall testee;
@Test
public void GIVEN_populated_with_millmetres_WHEN_millimetres_requested_THEN_returns_correct_value() {
testee = new Rainfall(new BigDecimal("2.5"));
| // Path: app/src/test/java/com/waynedgrant/cirrus/BigDecimalEquals.java
// public class BigDecimalEquals {
// public void assertEquals(BigDecimal expected, BigDecimal actual) {
// assertTrue(expected.compareTo(actual) == 0);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestRainfall.java
import com.waynedgrant.cirrus.BigDecimalEquals;
import com.waynedgrant.cirrus.units.RainfallUnit;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.measures;
public class TestRainfall {
private Rainfall testee;
@Test
public void GIVEN_populated_with_millmetres_WHEN_millimetres_requested_THEN_returns_correct_value() {
testee = new Rainfall(new BigDecimal("2.5"));
| new BigDecimalEquals().assertEquals(new BigDecimal("2.5"), testee.getValue(RainfallUnit.MILLIMETRES));
|
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java | // Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import static java.math.MathContext.DECIMAL32;
import com.waynedgrant.cirrus.units.RainfallUnit;
import java.math.BigDecimal;
| /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class Rainfall {
private BigDecimal millimetres;
private BigDecimal inches;
public Rainfall(BigDecimal millimetres) {
this.millimetres = millimetres;
this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
import static java.math.MathContext.DECIMAL32;
import com.waynedgrant.cirrus.units.RainfallUnit;
import java.math.BigDecimal;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.measures;
public class Rainfall {
private BigDecimal millimetres;
private BigDecimal inches;
public Rainfall(BigDecimal millimetres) {
this.millimetres = millimetres;
this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
}
| public BigDecimal getValue(RainfallUnit unit) {
|
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/measures/TestWindDirection.java | // Path: app/src/main/java/com/waynedgrant/cirrus/units/CardinalDirection.java
// public enum CardinalDirection {
// N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW
// }
| import com.waynedgrant.cirrus.units.CardinalDirection;
import org.junit.Test;
import static org.junit.Assert.assertEquals; | package com.waynedgrant.cirrus.measures;
public class TestWindDirection {
private WindDirection testee;
@Test
public void GIVEN_populated_with_compass_degrees_WHEN_degrees_requested_THEN_returns_correct_value() {
testee = new WindDirection(180);
assertEquals((Integer) 180, testee.getCompassDegrees());
}
@Test
public void GIVEN_populated_with_compass_degrees_WHEN_cardinal_direction_requested_THEN_returns_correct_value() {
testee = new WindDirection(0); | // Path: app/src/main/java/com/waynedgrant/cirrus/units/CardinalDirection.java
// public enum CardinalDirection {
// N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/measures/TestWindDirection.java
import com.waynedgrant.cirrus.units.CardinalDirection;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
package com.waynedgrant.cirrus.measures;
public class TestWindDirection {
private WindDirection testee;
@Test
public void GIVEN_populated_with_compass_degrees_WHEN_degrees_requested_THEN_returns_correct_value() {
testee = new WindDirection(180);
assertEquals((Integer) 180, testee.getCompassDegrees());
}
@Test
public void GIVEN_populated_with_compass_degrees_WHEN_cardinal_direction_requested_THEN_returns_correct_value() {
testee = new WindDirection(0); | assertEquals(CardinalDirection.N, testee.getCardinalDirection()); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/WindSpeedFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
// public class WindSpeed {
// private BigDecimal knots;
// private BigDecimal metresPerSecond;
// private BigDecimal kilometresPerHour;
// private BigDecimal milesPerHour;
// private BigDecimal beaufortScale;
//
// public WindSpeed(BigDecimal knots) {
// this.knots = knots;
// this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
// this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
// this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
// this.beaufortScale = convertKnotsToBeaufortScale(knots);
// }
//
// public BigDecimal getValue(WindSpeedUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case KNOTS:
// value = knots;
// break;
// case METRES_PER_SECOND:
// value = metresPerSecond;
// break;
// case KILOMETRES_PER_HOUR:
// value = kilometresPerHour;
// break;
// case MILES_PER_HOUR:
// value = milesPerHour;
// break;
// case BEAUFORT_SCALE:
// value = beaufortScale;
// break;
// }
//
// return value;
// }
//
// @SuppressWarnings("ConstantConditions")
// private BigDecimal convertKnotsToBeaufortScale(BigDecimal knots) {
// int roundedKnots = knots.setScale(0, RoundingMode.HALF_UP).intValue();
//
// int beaufortScale = 0;
//
// if (roundedKnots >= 1 && roundedKnots <= 3) {
// beaufortScale = 1;
// } else if (roundedKnots >= 4 && roundedKnots <= 6) {
// beaufortScale = 2;
// } else if (roundedKnots >= 7 && roundedKnots <= 10) {
// beaufortScale = 3;
// } else if (roundedKnots >= 11 && roundedKnots <= 16) {
// beaufortScale = 4;
// } else if (roundedKnots >= 17 && roundedKnots <= 21) {
// beaufortScale = 5;
// } else if (roundedKnots >= 22 && roundedKnots <= 27) {
// beaufortScale = 6;
// } else if (roundedKnots >= 28 && roundedKnots <= 33) {
// beaufortScale = 7;
// } else if (roundedKnots >= 34 && roundedKnots <= 40) {
// beaufortScale = 8;
// } else if (roundedKnots >= 41 && roundedKnots <= 47) {
// beaufortScale = 9;
// } else if (roundedKnots >= 48 && roundedKnots <= 55) {
// beaufortScale = 10;
// } else if (roundedKnots >= 56 && roundedKnots <= 63) {
// beaufortScale = 11;
// } else if (roundedKnots >= 64) {
// beaufortScale = 12;
// }
//
// return new BigDecimal(beaufortScale);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.WindSpeed;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.BEAUFORT_SCALE;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.KILOMETRES_PER_HOUR;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.KNOTS;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.METRES_PER_SECOND;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.MILES_PER_HOUR; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class WindSpeedFormatter {
private WindSpeed windSpeed;
public WindSpeedFormatter(WindSpeed windSpeed) {
this.windSpeed = windSpeed;
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/WindSpeed.java
// public class WindSpeed {
// private BigDecimal knots;
// private BigDecimal metresPerSecond;
// private BigDecimal kilometresPerHour;
// private BigDecimal milesPerHour;
// private BigDecimal beaufortScale;
//
// public WindSpeed(BigDecimal knots) {
// this.knots = knots;
// this.metresPerSecond = knots.multiply(new BigDecimal("0.514444"));
// this.kilometresPerHour = knots.multiply(new BigDecimal("1.852"));
// this.milesPerHour = knots.multiply(new BigDecimal("1.15078"));
// this.beaufortScale = convertKnotsToBeaufortScale(knots);
// }
//
// public BigDecimal getValue(WindSpeedUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case KNOTS:
// value = knots;
// break;
// case METRES_PER_SECOND:
// value = metresPerSecond;
// break;
// case KILOMETRES_PER_HOUR:
// value = kilometresPerHour;
// break;
// case MILES_PER_HOUR:
// value = milesPerHour;
// break;
// case BEAUFORT_SCALE:
// value = beaufortScale;
// break;
// }
//
// return value;
// }
//
// @SuppressWarnings("ConstantConditions")
// private BigDecimal convertKnotsToBeaufortScale(BigDecimal knots) {
// int roundedKnots = knots.setScale(0, RoundingMode.HALF_UP).intValue();
//
// int beaufortScale = 0;
//
// if (roundedKnots >= 1 && roundedKnots <= 3) {
// beaufortScale = 1;
// } else if (roundedKnots >= 4 && roundedKnots <= 6) {
// beaufortScale = 2;
// } else if (roundedKnots >= 7 && roundedKnots <= 10) {
// beaufortScale = 3;
// } else if (roundedKnots >= 11 && roundedKnots <= 16) {
// beaufortScale = 4;
// } else if (roundedKnots >= 17 && roundedKnots <= 21) {
// beaufortScale = 5;
// } else if (roundedKnots >= 22 && roundedKnots <= 27) {
// beaufortScale = 6;
// } else if (roundedKnots >= 28 && roundedKnots <= 33) {
// beaufortScale = 7;
// } else if (roundedKnots >= 34 && roundedKnots <= 40) {
// beaufortScale = 8;
// } else if (roundedKnots >= 41 && roundedKnots <= 47) {
// beaufortScale = 9;
// } else if (roundedKnots >= 48 && roundedKnots <= 55) {
// beaufortScale = 10;
// } else if (roundedKnots >= 56 && roundedKnots <= 63) {
// beaufortScale = 11;
// } else if (roundedKnots >= 64) {
// beaufortScale = 12;
// }
//
// return new BigDecimal(beaufortScale);
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/WindSpeedUnit.java
// public enum WindSpeedUnit {
// BEAUFORT_SCALE("Beaufort Scale (Bft)"),
// KILOMETRES_PER_HOUR("Kilometres per Hour (km/h)"),
// KNOTS("Knots (kts)"),
// METRES_PER_SECOND("Metres per Second (m/s)"),
// MILES_PER_HOUR("Miles per Hour (mph)");
//
// private String description;
//
// WindSpeedUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/WindSpeedFormatter.java
import com.waynedgrant.cirrus.measures.WindSpeed;
import com.waynedgrant.cirrus.units.WindSpeedUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.BEAUFORT_SCALE;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.KILOMETRES_PER_HOUR;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.KNOTS;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.METRES_PER_SECOND;
import static com.waynedgrant.cirrus.units.WindSpeedUnit.MILES_PER_HOUR;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class WindSpeedFormatter {
private WindSpeed windSpeed;
public WindSpeedFormatter(WindSpeed windSpeed) {
this.windSpeed = windSpeed;
}
| public String format(WindSpeedUnit unit) { |
waynedgrant/android-appwidget-cirrus | app/src/test/java/com/waynedgrant/cirrus/presentation/colorizers/TestTemperatureColorizer.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
| import static junit.framework.Assert.assertEquals;
import com.waynedgrant.cirrus.measures.Temperature;
import org.junit.Test;
import java.math.BigDecimal; | package com.waynedgrant.cirrus.presentation.colorizers;
public class TestTemperatureColorizer {
private TemperatureColorizer testee;
@Test
public void GIVEN_null_temperature_WHEN_color_requested_THEN_white_color_returned() {
testee = new TemperatureColorizer(null);
assertEquals(TemperatureColorizer.WHITE, testee.colorize());
}
@Test
public void GIVEN_temperature_less_than_0_point_6_degrees_celsius_WHEN_color_requested_THEN_light_blue_color_returned() { | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Temperature.java
// public class Temperature {
// private BigDecimal celsius;
// private BigDecimal fahrenheit;
//
// public Temperature(BigDecimal celsius) {
// this.celsius = celsius;
// this.fahrenheit = (celsius.multiply(new BigDecimal("1.8"))).add(new BigDecimal("32"));
// }
//
// public BigDecimal getValue(TemperatureUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case CELSIUS:
// value = celsius;
// break;
// case FAHRENHEIT:
// value = fahrenheit;
// break;
// }
//
// return value;
// }
// }
// Path: app/src/test/java/com/waynedgrant/cirrus/presentation/colorizers/TestTemperatureColorizer.java
import static junit.framework.Assert.assertEquals;
import com.waynedgrant.cirrus.measures.Temperature;
import org.junit.Test;
import java.math.BigDecimal;
package com.waynedgrant.cirrus.presentation.colorizers;
public class TestTemperatureColorizer {
private TemperatureColorizer testee;
@Test
public void GIVEN_null_temperature_WHEN_color_requested_THEN_white_color_returned() {
testee = new TemperatureColorizer(null);
assertEquals(TemperatureColorizer.WHITE, testee.colorize());
}
@Test
public void GIVEN_temperature_less_than_0_point_6_degrees_celsius_WHEN_color_requested_THEN_light_blue_color_returned() { | testee = new TemperatureColorizer(new Temperature(new BigDecimal("0.5"))); |
waynedgrant/android-appwidget-cirrus | app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/RainfallRateFormatter.java | // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
| import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.RainfallUnit.MILLIMETRES; | /* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class RainfallRateFormatter {
private Rainfall rainfallRatePerMinute;
public RainfallRateFormatter(Rainfall rainfallRatePerMinute) {
this.rainfallRatePerMinute = rainfallRatePerMinute;
}
| // Path: app/src/main/java/com/waynedgrant/cirrus/measures/Rainfall.java
// public class Rainfall {
// private BigDecimal millimetres;
// private BigDecimal inches;
//
// public Rainfall(BigDecimal millimetres) {
// this.millimetres = millimetres;
// this.inches = this.millimetres.multiply(new BigDecimal("1").divide(new BigDecimal("25.4"), DECIMAL32));
// }
//
// public BigDecimal getValue(RainfallUnit unit) {
// BigDecimal value = null;
//
// switch (unit) {
// case MILLIMETRES:
// value = millimetres;
// break;
// case INCHES:
// value = inches;
// break;
// }
//
// return value;
// }
// }
//
// Path: app/src/main/java/com/waynedgrant/cirrus/units/RainfallUnit.java
// public enum RainfallUnit {
// INCHES("Inches (in)"),
// MILLIMETRES("Millimetres (mm)");
//
// private String description;
//
// RainfallUnit(String description) {
// this.description = description;
// }
//
// public String toString() {
// return description;
// }
// }
// Path: app/src/main/java/com/waynedgrant/cirrus/presentation/formatters/RainfallRateFormatter.java
import com.waynedgrant.cirrus.measures.Rainfall;
import com.waynedgrant.cirrus.units.RainfallUnit;
import java.math.RoundingMode;
import java.util.Locale;
import static com.waynedgrant.cirrus.units.RainfallUnit.MILLIMETRES;
/* Copyright 2017 Wayne D Grant (www.waynedgrant.com)
Licensed under the MIT License */
package com.waynedgrant.cirrus.presentation.formatters;
public class RainfallRateFormatter {
private Rainfall rainfallRatePerMinute;
public RainfallRateFormatter(Rainfall rainfallRatePerMinute) {
this.rainfallRatePerMinute = rainfallRatePerMinute;
}
| public String format(RainfallUnit unit) { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForServiceTicketValidatedEvents.java | // Path: src/main/java/net/unicon/cas/addons/info/events/CasServiceTicketValidatedEvent.java
// public final class CasServiceTicketValidatedEvent extends AbstractCasServiceAccessEvent {
//
// private final Assertion assertion;
//
// public CasServiceTicketValidatedEvent(Object source, String serviceTicketId, Service service, Assertion assertion) {
// super(source, serviceTicketId, service);
// this.assertion = assertion;
// }
//
// public Assertion getAssertion() {
// return assertion;
// }
//
// @Override
// public String toString() {
// return super.toString() + " -- {assertion=" + assertion + "}";
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/info/events/CasSsoSessionEstablishedEvent.java
// public final class CasSsoSessionEstablishedEvent extends AbstractCasSsoEvent {
//
// public CasSsoSessionEstablishedEvent(Object source, Authentication authentication, String ticketGrantingTicketId) {
// super(source, authentication, ticketGrantingTicketId);
// }
// }
| import net.unicon.cas.addons.info.events.CasServiceTicketValidatedEvent;
import net.unicon.cas.addons.info.events.CasSsoSessionEstablishedEvent;
import net.unicon.cas.addons.support.ThreadSafe;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate; | package net.unicon.cas.addons.info.events.listeners;
/**
* An event listener for <code>CasServiceTicketValidatedEvent</code>s that records daily counts for each event by atomically incrementing a value in
* Redis server under a <i>cas:st-validated:yyyy-MM-dd</i> key.
* <p/>
* This class assumes a live Redis server running and depends on an instance of <code>org.springframework.data.redis.connection.jedis.JedisConnectionFactory</code>
* of spring data redis module, from which it constructs an instance of <code>org.springframework.data.redis.core.StringRedisTemplate</code>.
* <p/>
* At runtime if a Redis server becomes unavailable or any other exceptions are thrown during server access, a WARN level log message logs the exception and execution path
* of CAS server continues.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.9
*/
@ThreadSafe
public class RedisStatsRecorderForServiceTicketValidatedEvents implements | // Path: src/main/java/net/unicon/cas/addons/info/events/CasServiceTicketValidatedEvent.java
// public final class CasServiceTicketValidatedEvent extends AbstractCasServiceAccessEvent {
//
// private final Assertion assertion;
//
// public CasServiceTicketValidatedEvent(Object source, String serviceTicketId, Service service, Assertion assertion) {
// super(source, serviceTicketId, service);
// this.assertion = assertion;
// }
//
// public Assertion getAssertion() {
// return assertion;
// }
//
// @Override
// public String toString() {
// return super.toString() + " -- {assertion=" + assertion + "}";
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/info/events/CasSsoSessionEstablishedEvent.java
// public final class CasSsoSessionEstablishedEvent extends AbstractCasSsoEvent {
//
// public CasSsoSessionEstablishedEvent(Object source, Authentication authentication, String ticketGrantingTicketId) {
// super(source, authentication, ticketGrantingTicketId);
// }
// }
// Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForServiceTicketValidatedEvents.java
import net.unicon.cas.addons.info.events.CasServiceTicketValidatedEvent;
import net.unicon.cas.addons.info.events.CasSsoSessionEstablishedEvent;
import net.unicon.cas.addons.support.ThreadSafe;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
package net.unicon.cas.addons.info.events.listeners;
/**
* An event listener for <code>CasServiceTicketValidatedEvent</code>s that records daily counts for each event by atomically incrementing a value in
* Redis server under a <i>cas:st-validated:yyyy-MM-dd</i> key.
* <p/>
* This class assumes a live Redis server running and depends on an instance of <code>org.springframework.data.redis.connection.jedis.JedisConnectionFactory</code>
* of spring data redis module, from which it constructs an instance of <code>org.springframework.data.redis.core.StringRedisTemplate</code>.
* <p/>
* At runtime if a Redis server becomes unavailable or any other exceptions are thrown during server access, a WARN level log message logs the exception and execution path
* of CAS server continues.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.9
*/
@ThreadSafe
public class RedisStatsRecorderForServiceTicketValidatedEvents implements | ApplicationListener<CasServiceTicketValidatedEvent> { |
Unicon/cas-addons | src/test/java/net/unicon/cas/addons/config/CasNamespaceReadWriteJsonServiceRegistryDaoParserTests.java | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/ReadWriteJsonServiceRegistryDao.java
// public final class ReadWriteJsonServiceRegistryDao extends JsonServiceRegistryDao {
//
// public ReadWriteJsonServiceRegistryDao(final Resource servicesConfigFile) {
// super(servicesConfigFile);
// this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// }
//
// @Override
// protected RegisteredService saveInternal(final RegisteredService registeredService) {
// logger.debug("Loading service definitions from resource [{}]", this.servicesConfigFile.getFilename());
// final List<RegisteredService> resolvedServices = super.loadServices();
// final List<RegisteredService> col = new ArrayList<RegisteredService>(resolvedServices);
//
// if (registeredService.getId() < 0) {
// if (registeredService instanceof AbstractRegisteredService) {
// final Random random = new Random(registeredService.hashCode());
// final int serviceId = random.nextInt(Integer.MAX_VALUE);
// ((AbstractRegisteredService) registeredService).setId(serviceId);
// }
// }
// boolean foundAndRemovedService = false;
// final Iterator<RegisteredService> it = col.iterator();
// while(!foundAndRemovedService && it.hasNext()) {
// if (it.next().getId() == registeredService.getId()) {
// it.remove();
// foundAndRemovedService = true;
// }
// }
// col.add(registeredService);
//
// saveListOfRegisteredServices(col);
// return registeredService;
// }
//
// @Override
// protected boolean deleteInternal(final RegisteredService registeredService) {
// logger.debug("Loading service definitions from resource [{}]", this.servicesConfigFile.getFilename());
// final List<RegisteredService> resolvedServices = super.loadServices();
// final RegisteredService regServiceToDelete = findServiceById(registeredService.getId());
//
// if (regServiceToDelete != null) {
// logger.debug("Found service definition to remove: [{}]", regServiceToDelete);
// final List<RegisteredService> col = new ArrayList<RegisteredService>(resolvedServices);
// col.remove(regServiceToDelete);
//
// saveListOfRegisteredServices(col);
// return true;
// }
// return false;
// }
//
// private void saveListOfRegisteredServices(final List<RegisteredService> col) {
// OutputStream out = null;
// FileOutputStream fout = null;
//
// try {
// fout = new FileOutputStream(this.servicesConfigFile.getFile());
// out = new BufferedOutputStream(fout);
//
// final Map<String, Object> map = new LinkedHashMap<String, Object>(col.size());
// map.put(SERVICES_KEY, col);
//
// logger.debug("Writing [{}] service definitions to resource [{}]", col.size(), this.servicesConfigFile.getFilename());
// this.objectMapper.writerWithDefaultPrettyPrinter().writeValue(out, map);
//
// fout.flush();
// out.flush();
//
// } catch (final Exception e) {
// logger.error(e.getMessage(), e);
// } finally {
// IOUtils.closeQuietly(fout);
// IOUtils.closeQuietly(out);
// }
// }
// }
| import net.unicon.cas.addons.serviceregistry.ReadWriteJsonServiceRegistryDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue; | package net.unicon.cas.addons.config;
/**
* @author Dmitriy Kopylenko
* @author Unicon, inc.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CasNamespaceReadWriteJsonServiceRegistryDaoParserTests {
@Autowired
ApplicationContext applicationContext;
private static final String SERVICE_REGISTRY_DAO_BEAN_NAME = "serviceRegistryDao";
@Test
public void readWriteJsonServiceRegistryDaoBeanDefinitionCorrectlyParsed() {
assertTrue(applicationContext.containsBean(SERVICE_REGISTRY_DAO_BEAN_NAME)); | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/ReadWriteJsonServiceRegistryDao.java
// public final class ReadWriteJsonServiceRegistryDao extends JsonServiceRegistryDao {
//
// public ReadWriteJsonServiceRegistryDao(final Resource servicesConfigFile) {
// super(servicesConfigFile);
// this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// }
//
// @Override
// protected RegisteredService saveInternal(final RegisteredService registeredService) {
// logger.debug("Loading service definitions from resource [{}]", this.servicesConfigFile.getFilename());
// final List<RegisteredService> resolvedServices = super.loadServices();
// final List<RegisteredService> col = new ArrayList<RegisteredService>(resolvedServices);
//
// if (registeredService.getId() < 0) {
// if (registeredService instanceof AbstractRegisteredService) {
// final Random random = new Random(registeredService.hashCode());
// final int serviceId = random.nextInt(Integer.MAX_VALUE);
// ((AbstractRegisteredService) registeredService).setId(serviceId);
// }
// }
// boolean foundAndRemovedService = false;
// final Iterator<RegisteredService> it = col.iterator();
// while(!foundAndRemovedService && it.hasNext()) {
// if (it.next().getId() == registeredService.getId()) {
// it.remove();
// foundAndRemovedService = true;
// }
// }
// col.add(registeredService);
//
// saveListOfRegisteredServices(col);
// return registeredService;
// }
//
// @Override
// protected boolean deleteInternal(final RegisteredService registeredService) {
// logger.debug("Loading service definitions from resource [{}]", this.servicesConfigFile.getFilename());
// final List<RegisteredService> resolvedServices = super.loadServices();
// final RegisteredService regServiceToDelete = findServiceById(registeredService.getId());
//
// if (regServiceToDelete != null) {
// logger.debug("Found service definition to remove: [{}]", regServiceToDelete);
// final List<RegisteredService> col = new ArrayList<RegisteredService>(resolvedServices);
// col.remove(regServiceToDelete);
//
// saveListOfRegisteredServices(col);
// return true;
// }
// return false;
// }
//
// private void saveListOfRegisteredServices(final List<RegisteredService> col) {
// OutputStream out = null;
// FileOutputStream fout = null;
//
// try {
// fout = new FileOutputStream(this.servicesConfigFile.getFile());
// out = new BufferedOutputStream(fout);
//
// final Map<String, Object> map = new LinkedHashMap<String, Object>(col.size());
// map.put(SERVICES_KEY, col);
//
// logger.debug("Writing [{}] service definitions to resource [{}]", col.size(), this.servicesConfigFile.getFilename());
// this.objectMapper.writerWithDefaultPrettyPrinter().writeValue(out, map);
//
// fout.flush();
// out.flush();
//
// } catch (final Exception e) {
// logger.error(e.getMessage(), e);
// } finally {
// IOUtils.closeQuietly(fout);
// IOUtils.closeQuietly(out);
// }
// }
// }
// Path: src/test/java/net/unicon/cas/addons/config/CasNamespaceReadWriteJsonServiceRegistryDaoParserTests.java
import net.unicon.cas.addons.serviceregistry.ReadWriteJsonServiceRegistryDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue;
package net.unicon.cas.addons.config;
/**
* @author Dmitriy Kopylenko
* @author Unicon, inc.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CasNamespaceReadWriteJsonServiceRegistryDaoParserTests {
@Autowired
ApplicationContext applicationContext;
private static final String SERVICE_REGISTRY_DAO_BEAN_NAME = "serviceRegistryDao";
@Test
public void readWriteJsonServiceRegistryDaoBeanDefinitionCorrectlyParsed() {
assertTrue(applicationContext.containsBean(SERVICE_REGISTRY_DAO_BEAN_NAME)); | assertTrue(applicationContext.getBeansOfType(ReadWriteJsonServiceRegistryDao.class).size() == 1); |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/web/flow/InMemoryServiceRedirectionByClientIpAddressAdvisor.java | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
| import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.execution.RequestContext; | /**
*
*/
package net.unicon.cas.addons.web.flow;
/**
* An extension of the {@link ServiceRedirectionAdvisor} that bases the calculation of url redirection off
* of the client remote address and port. If the remote address, port, service or the redirect url change, then
* this component would indicate that the interruption is required. Otherwise, proceeds as normal.
*
* <p>State data is kept in memory only.</p>
*
* @author Misagh Moayyed (<a href="mailto:[email protected]">[email protected]</a>)
* @since 1.9
*/
public final class InMemoryServiceRedirectionByClientIpAddressAdvisor implements ServiceRedirectionAdvisor {
private static final Logger logger = LoggerFactory.getLogger(InMemoryServiceRedirectionByClientIpAddressAdvisor.class);
private final Set<String> repository = new HashSet<String>();
@Override
public boolean shouldRedirectServiceRequest(final RequestContext context, | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
// Path: src/main/java/net/unicon/cas/addons/web/flow/InMemoryServiceRedirectionByClientIpAddressAdvisor.java
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.execution.RequestContext;
/**
*
*/
package net.unicon.cas.addons.web.flow;
/**
* An extension of the {@link ServiceRedirectionAdvisor} that bases the calculation of url redirection off
* of the client remote address and port. If the remote address, port, service or the redirect url change, then
* this component would indicate that the interruption is required. Otherwise, proceeds as normal.
*
* <p>State data is kept in memory only.</p>
*
* @author Misagh Moayyed (<a href="mailto:[email protected]">[email protected]</a>)
* @since 1.9
*/
public final class InMemoryServiceRedirectionByClientIpAddressAdvisor implements ServiceRedirectionAdvisor {
private static final Logger logger = LoggerFactory.getLogger(InMemoryServiceRedirectionByClientIpAddressAdvisor.class);
private final Set<String> repository = new HashSet<String>();
@Override
public boolean shouldRedirectServiceRequest(final RequestContext context, | final RegisteredServiceWithAttributes service, |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
| import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import java.util.Collection;
import java.util.Map; | package net.unicon.cas.addons.info;
/**
* An API to provide an aggregate view of CAS' <i>live</i> SSO sessions at run time i.e. a collection of
* un-expired <code>TicketGrantingTicket</code>'s metadata and their associated <code>Authentication</code> data.
* <p/>
* Note that this view is just a snapshot of active sessions at the time of call, and might not represent a true
* view of unexpired sessions by the time it is presented to clients.
* <p/>
* This API returns an un-typed view of this data in a form of <code>Map<String, Object</code> which adds a flexibility
* to clients to render it however they choose. As a convenience, this interface also exposes an Enum of the map keys
* it expects implementors to use.
* <p/>
* Note: this API is only intended to be called by CAS server code e.g. any custom CAS server overlay extension, etc.
* <p/>
* Concurrency semantics: implementations must be thread safe.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
public interface SingleSignOnSessionsReport {
enum SsoSessionAttributeKeys {
AUTHENTICATED_PRINCIPAL("authenticated_principal"),
AUTHENTICATION_DATE("authentication_date"),
NUMBER_OF_USES("number_of_uses");
private String attributeKey;
private SsoSessionAttributeKeys(String attributeKey) {
this.attributeKey = attributeKey;
}
@Override
public String toString() {
return this.attributeKey;
}
}
/**
* Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
* <p/>
* If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
*
* @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
* no active SSO sessions
*/ | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
// Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import java.util.Collection;
import java.util.Map;
package net.unicon.cas.addons.info;
/**
* An API to provide an aggregate view of CAS' <i>live</i> SSO sessions at run time i.e. a collection of
* un-expired <code>TicketGrantingTicket</code>'s metadata and their associated <code>Authentication</code> data.
* <p/>
* Note that this view is just a snapshot of active sessions at the time of call, and might not represent a true
* view of unexpired sessions by the time it is presented to clients.
* <p/>
* This API returns an un-typed view of this data in a form of <code>Map<String, Object</code> which adds a flexibility
* to clients to render it however they choose. As a convenience, this interface also exposes an Enum of the map keys
* it expects implementors to use.
* <p/>
* Note: this API is only intended to be called by CAS server code e.g. any custom CAS server overlay extension, etc.
* <p/>
* Concurrency semantics: implementations must be thread safe.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
public interface SingleSignOnSessionsReport {
enum SsoSessionAttributeKeys {
AUTHENTICATED_PRINCIPAL("authenticated_principal"),
AUTHENTICATION_DATE("authentication_date"),
NUMBER_OF_USES("number_of_uses");
private String attributeKey;
private SsoSessionAttributeKeys(String attributeKey) {
this.attributeKey = attributeKey;
}
@Override
public String toString() {
return this.attributeKey;
}
}
/**
* Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
* <p/>
* If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
*
* @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
* no active SSO sessions
*/ | Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/serviceregistry/services/authorization/ServiceAuthorizationAction.java | // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
//
// Path: src/main/java/net/unicon/cas/addons/authentication/internal/DefaultAuthenticationSupport.java
// public class DefaultAuthenticationSupport implements AuthenticationSupport {
//
// private TicketRegistry ticketRegistry;
//
// public DefaultAuthenticationSupport(TicketRegistry ticketRegistry) {
// this.ticketRegistry = ticketRegistry;
// }
//
// @Override
// /** {@inheritDoc} */
// public Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException {
// TicketGrantingTicket tgt = (TicketGrantingTicket) this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
// return tgt == null ? null : tgt.getAuthentication();
// }
//
// @Override
// /** {@inheritDoc} */
// public Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException {
// Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
// return auth == null ? null : auth.getPrincipal();
// }
//
// @Override
// /** {@inheritDoc} */
// public Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException {
// Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId);
// return principal == null ? null : principal.getAttributes();
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
| import net.unicon.cas.addons.authentication.AuthenticationSupport;
import net.unicon.cas.addons.authentication.internal.DefaultAuthenticationSupport;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.WebUtils;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext; | package net.unicon.cas.addons.serviceregistry.services.authorization;
/**
* An action state to be executed for the authorization check based on registered service attributes before vending a service ticket.
* <p/>
* It is expected that this action is to be inserted as the first action of the <code>generateServiceTicket</code> action state in the login web flow definition.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.5
*/
public class ServiceAuthorizationAction extends AbstractAction {
private final ServicesManager servicesManager;
private final RegisteredServiceAuthorizer authorizer;
| // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
//
// Path: src/main/java/net/unicon/cas/addons/authentication/internal/DefaultAuthenticationSupport.java
// public class DefaultAuthenticationSupport implements AuthenticationSupport {
//
// private TicketRegistry ticketRegistry;
//
// public DefaultAuthenticationSupport(TicketRegistry ticketRegistry) {
// this.ticketRegistry = ticketRegistry;
// }
//
// @Override
// /** {@inheritDoc} */
// public Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException {
// TicketGrantingTicket tgt = (TicketGrantingTicket) this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
// return tgt == null ? null : tgt.getAuthentication();
// }
//
// @Override
// /** {@inheritDoc} */
// public Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException {
// Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
// return auth == null ? null : auth.getPrincipal();
// }
//
// @Override
// /** {@inheritDoc} */
// public Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException {
// Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId);
// return principal == null ? null : principal.getAttributes();
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/authorization/ServiceAuthorizationAction.java
import net.unicon.cas.addons.authentication.AuthenticationSupport;
import net.unicon.cas.addons.authentication.internal.DefaultAuthenticationSupport;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.WebUtils;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
package net.unicon.cas.addons.serviceregistry.services.authorization;
/**
* An action state to be executed for the authorization check based on registered service attributes before vending a service ticket.
* <p/>
* It is expected that this action is to be inserted as the first action of the <code>generateServiceTicket</code> action state in the login web flow definition.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.5
*/
public class ServiceAuthorizationAction extends AbstractAction {
private final ServicesManager servicesManager;
private final RegisteredServiceAuthorizer authorizer;
| private final AuthenticationSupport authenticationSupport; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/serviceregistry/services/authorization/ServiceAuthorizationAction.java | // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
//
// Path: src/main/java/net/unicon/cas/addons/authentication/internal/DefaultAuthenticationSupport.java
// public class DefaultAuthenticationSupport implements AuthenticationSupport {
//
// private TicketRegistry ticketRegistry;
//
// public DefaultAuthenticationSupport(TicketRegistry ticketRegistry) {
// this.ticketRegistry = ticketRegistry;
// }
//
// @Override
// /** {@inheritDoc} */
// public Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException {
// TicketGrantingTicket tgt = (TicketGrantingTicket) this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
// return tgt == null ? null : tgt.getAuthentication();
// }
//
// @Override
// /** {@inheritDoc} */
// public Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException {
// Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
// return auth == null ? null : auth.getPrincipal();
// }
//
// @Override
// /** {@inheritDoc} */
// public Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException {
// Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId);
// return principal == null ? null : principal.getAttributes();
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
| import net.unicon.cas.addons.authentication.AuthenticationSupport;
import net.unicon.cas.addons.authentication.internal.DefaultAuthenticationSupport;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.WebUtils;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext; | package net.unicon.cas.addons.serviceregistry.services.authorization;
/**
* An action state to be executed for the authorization check based on registered service attributes before vending a service ticket.
* <p/>
* It is expected that this action is to be inserted as the first action of the <code>generateServiceTicket</code> action state in the login web flow definition.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.5
*/
public class ServiceAuthorizationAction extends AbstractAction {
private final ServicesManager servicesManager;
private final RegisteredServiceAuthorizer authorizer;
private final AuthenticationSupport authenticationSupport;
private static final String AUTHZ_ATTRS_KEY = "authzAttributes";
private static final String AUTHZ_FAIL_REDIRECT_URL_KEY = "authorizationFailureRedirectUrl";
private static final String ATTR_URL_KEY = "unauthorizedRedirectUrl";
private static final Logger logger = LoggerFactory.getLogger(ServiceAuthorizationAction.class);
public ServiceAuthorizationAction(final ServicesManager servicesManager, final TicketRegistry ticketRegistry, final RegisteredServiceAuthorizer registeredServiceAuthorizer) {
this.servicesManager = servicesManager;
this.authorizer = registeredServiceAuthorizer; | // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
//
// Path: src/main/java/net/unicon/cas/addons/authentication/internal/DefaultAuthenticationSupport.java
// public class DefaultAuthenticationSupport implements AuthenticationSupport {
//
// private TicketRegistry ticketRegistry;
//
// public DefaultAuthenticationSupport(TicketRegistry ticketRegistry) {
// this.ticketRegistry = ticketRegistry;
// }
//
// @Override
// /** {@inheritDoc} */
// public Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException {
// TicketGrantingTicket tgt = (TicketGrantingTicket) this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
// return tgt == null ? null : tgt.getAuthentication();
// }
//
// @Override
// /** {@inheritDoc} */
// public Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException {
// Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
// return auth == null ? null : auth.getPrincipal();
// }
//
// @Override
// /** {@inheritDoc} */
// public Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException {
// Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId);
// return principal == null ? null : principal.getAttributes();
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/authorization/ServiceAuthorizationAction.java
import net.unicon.cas.addons.authentication.AuthenticationSupport;
import net.unicon.cas.addons.authentication.internal.DefaultAuthenticationSupport;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.WebUtils;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
package net.unicon.cas.addons.serviceregistry.services.authorization;
/**
* An action state to be executed for the authorization check based on registered service attributes before vending a service ticket.
* <p/>
* It is expected that this action is to be inserted as the first action of the <code>generateServiceTicket</code> action state in the login web flow definition.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.5
*/
public class ServiceAuthorizationAction extends AbstractAction {
private final ServicesManager servicesManager;
private final RegisteredServiceAuthorizer authorizer;
private final AuthenticationSupport authenticationSupport;
private static final String AUTHZ_ATTRS_KEY = "authzAttributes";
private static final String AUTHZ_FAIL_REDIRECT_URL_KEY = "authorizationFailureRedirectUrl";
private static final String ATTR_URL_KEY = "unauthorizedRedirectUrl";
private static final Logger logger = LoggerFactory.getLogger(ServiceAuthorizationAction.class);
public ServiceAuthorizationAction(final ServicesManager servicesManager, final TicketRegistry ticketRegistry, final RegisteredServiceAuthorizer registeredServiceAuthorizer) {
this.servicesManager = servicesManager;
this.authorizer = registeredServiceAuthorizer; | this.authenticationSupport = new DefaultAuthenticationSupport(ticketRegistry); |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/serviceregistry/services/authorization/ServiceAuthorizationAction.java | // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
//
// Path: src/main/java/net/unicon/cas/addons/authentication/internal/DefaultAuthenticationSupport.java
// public class DefaultAuthenticationSupport implements AuthenticationSupport {
//
// private TicketRegistry ticketRegistry;
//
// public DefaultAuthenticationSupport(TicketRegistry ticketRegistry) {
// this.ticketRegistry = ticketRegistry;
// }
//
// @Override
// /** {@inheritDoc} */
// public Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException {
// TicketGrantingTicket tgt = (TicketGrantingTicket) this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
// return tgt == null ? null : tgt.getAuthentication();
// }
//
// @Override
// /** {@inheritDoc} */
// public Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException {
// Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
// return auth == null ? null : auth.getPrincipal();
// }
//
// @Override
// /** {@inheritDoc} */
// public Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException {
// Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId);
// return principal == null ? null : principal.getAttributes();
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
| import net.unicon.cas.addons.authentication.AuthenticationSupport;
import net.unicon.cas.addons.authentication.internal.DefaultAuthenticationSupport;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.WebUtils;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext; | this.servicesManager = servicesManager;
this.authorizer = registeredServiceAuthorizer;
this.authenticationSupport = new DefaultAuthenticationSupport(ticketRegistry);
}
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
final Principal principal = this.authenticationSupport.getAuthenticatedPrincipalFrom(WebUtils.getTicketGrantingTicketId(requestContext));
//Guard against expired SSO sessions. 'error' event should trigger the transition to the 'generateLoginTicket' state
if (principal == null) {
logger.warn("The SSO session is no longer valid. Restarting the login process...");
return error();
}
final Object principalAttributes = principal.getAttributes();
final String principalId = principal.getId();
final Service service = WebUtils.getService(requestContext);
final String serviceId = service.getId();
//Find this service in the service registry
final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
if (registeredService == null) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not defined in the service registry.", serviceId);
throw new UnauthorizedServiceException();
}
else if (!registeredService.isEnabled()) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not enabled in the service registry.", serviceId);
throw new UnauthorizedServiceException();
}
| // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
//
// Path: src/main/java/net/unicon/cas/addons/authentication/internal/DefaultAuthenticationSupport.java
// public class DefaultAuthenticationSupport implements AuthenticationSupport {
//
// private TicketRegistry ticketRegistry;
//
// public DefaultAuthenticationSupport(TicketRegistry ticketRegistry) {
// this.ticketRegistry = ticketRegistry;
// }
//
// @Override
// /** {@inheritDoc} */
// public Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException {
// TicketGrantingTicket tgt = (TicketGrantingTicket) this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
// return tgt == null ? null : tgt.getAuthentication();
// }
//
// @Override
// /** {@inheritDoc} */
// public Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException {
// Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
// return auth == null ? null : auth.getPrincipal();
// }
//
// @Override
// /** {@inheritDoc} */
// public Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException {
// Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId);
// return principal == null ? null : principal.getAttributes();
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/authorization/ServiceAuthorizationAction.java
import net.unicon.cas.addons.authentication.AuthenticationSupport;
import net.unicon.cas.addons.authentication.internal.DefaultAuthenticationSupport;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.WebUtils;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
this.servicesManager = servicesManager;
this.authorizer = registeredServiceAuthorizer;
this.authenticationSupport = new DefaultAuthenticationSupport(ticketRegistry);
}
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
final Principal principal = this.authenticationSupport.getAuthenticatedPrincipalFrom(WebUtils.getTicketGrantingTicketId(requestContext));
//Guard against expired SSO sessions. 'error' event should trigger the transition to the 'generateLoginTicket' state
if (principal == null) {
logger.warn("The SSO session is no longer valid. Restarting the login process...");
return error();
}
final Object principalAttributes = principal.getAttributes();
final String principalId = principal.getId();
final Service service = WebUtils.getService(requestContext);
final String serviceId = service.getId();
//Find this service in the service registry
final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
if (registeredService == null) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not defined in the service registry.", serviceId);
throw new UnauthorizedServiceException();
}
else if (!registeredService.isEnabled()) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not enabled in the service registry.", serviceId);
throw new UnauthorizedServiceException();
}
| if (!(registeredService instanceof RegisteredServiceWithAttributes)) { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/serviceregistry/JsonServiceRegistryDao.java | // Path: src/main/java/net/unicon/cas/addons/support/ResourceChangeDetectingEventNotifier.java
// public class ResourceChangeDetectingEventNotifier implements ApplicationEventPublisherAware {
//
// /**
// * Application event representing the resource contents change.
// * Intended to be processed by subscribed <code>ApplicationListener</code>s
// * managed by ApplicationContext.
// */
// public static class ResourceChangedEvent extends ApplicationEvent {
// private static final long serialVersionUID = 1L;
//
// private final URI resourceUri;
//
// public ResourceChangedEvent(final Object source, final URI resourceUri) {
// super(source);
// this.resourceUri = resourceUri;
// }
//
// public URI getResourceUri() {
// return this.resourceUri;
// }
// }
//
// private ApplicationEventPublisher applicationEventPublisher;
//
// private final Resource watchedResource;
//
// private volatile String resourceSha1Hex;
//
// private static final Logger logger = LoggerFactory.getLogger(ResourceChangeDetectingEventNotifier.class);
//
// private static final String EMPTY_STRING_SHA1 = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
//
// public ResourceChangeDetectingEventNotifier(final Resource watchedResource) throws Exception {
// this.watchedResource = watchedResource;
// if (!this.watchedResource.exists()) {
// throw new BeanCreationException(String.format("The 'watchedResource' [%s] must point to an existing resource. " +
// "Please double-check that such resource exists.", this.watchedResource.getURI()));
// }
// //Initial SHA1 of the resource
// //TODO: currently assumes file-based resources. Think about refactoring later to support diff kinds of resources?
// final String initialSha1Hex = new Sha1Hash(this.watchedResource.getFile()).toHex();
// if (EMPTY_STRING_SHA1.equals(initialSha1Hex)) {
// logger.warn("The 'watchedResource' [{}] is empty!", this.watchedResource.getURI());
// }
// this.resourceSha1Hex = initialSha1Hex;
// }
//
// /**
// * Compare the SHA1 digests (since last check and the latest) of the configured resource, and if change is detected,
// * publish the <code>ResourceChangeEvent</code> to ApplicationContext.
// */
// public void notifyOfTheResourceChangeEventIfNecessary() {
// final String currentResourceSha1 = this.resourceSha1Hex;
// String newResourceSha1 = null;
// try {
// newResourceSha1 = new Sha1Hash(this.watchedResource.getFile()).toHex();
// if (!newResourceSha1.equals(currentResourceSha1)) {
// logger.debug("Resource: [{}] | Old Hash: [{}] | New Hash: [{}]", new Object[] {this.watchedResource.getURI(), currentResourceSha1, newResourceSha1});
// synchronized (this.resourceSha1Hex) {
// this.resourceSha1Hex = newResourceSha1;
// this.applicationEventPublisher.publishEvent(new ResourceChangedEvent(this, this.watchedResource.getURI()));
// }
// }
// }
// catch (final Throwable e) {
// //TODO: Possibly introduce an exception handling strategy?
// logger.error("An exception is caught during 'watchedResource' access", e);
// return;
// }
// }
//
// @Override
// public void setApplicationEventPublisher(final ApplicationEventPublisher applicationEventPublisher) {
// this.applicationEventPublisher = applicationEventPublisher;
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import net.unicon.cas.addons.support.GuardedBy;
import net.unicon.cas.addons.support.ResourceChangeDetectingEventNotifier;
import net.unicon.cas.addons.support.ThreadSafe;
import org.jasig.cas.services.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; | package net.unicon.cas.addons.serviceregistry;
/**
* Implementation of <code>ServiceRegistryDao</code> that reads services definition from JSON configuration file at the Spring Application Context
* initialization time. After un-marshaling services from JSON blob, delegates the storage and retrieval to <code>InMemoryServiceRegistryDaoImpl</code>
* <p/>
* This class implements ${link ApplicationListener<ResourceChangeDetectingEventNotifier.ResourceChangedEvent>} to reload services definitions in real-time.
* This class is thread safe.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 0.8
*/
@ThreadSafe
public class JsonServiceRegistryDao implements ServiceRegistryDao, | // Path: src/main/java/net/unicon/cas/addons/support/ResourceChangeDetectingEventNotifier.java
// public class ResourceChangeDetectingEventNotifier implements ApplicationEventPublisherAware {
//
// /**
// * Application event representing the resource contents change.
// * Intended to be processed by subscribed <code>ApplicationListener</code>s
// * managed by ApplicationContext.
// */
// public static class ResourceChangedEvent extends ApplicationEvent {
// private static final long serialVersionUID = 1L;
//
// private final URI resourceUri;
//
// public ResourceChangedEvent(final Object source, final URI resourceUri) {
// super(source);
// this.resourceUri = resourceUri;
// }
//
// public URI getResourceUri() {
// return this.resourceUri;
// }
// }
//
// private ApplicationEventPublisher applicationEventPublisher;
//
// private final Resource watchedResource;
//
// private volatile String resourceSha1Hex;
//
// private static final Logger logger = LoggerFactory.getLogger(ResourceChangeDetectingEventNotifier.class);
//
// private static final String EMPTY_STRING_SHA1 = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
//
// public ResourceChangeDetectingEventNotifier(final Resource watchedResource) throws Exception {
// this.watchedResource = watchedResource;
// if (!this.watchedResource.exists()) {
// throw new BeanCreationException(String.format("The 'watchedResource' [%s] must point to an existing resource. " +
// "Please double-check that such resource exists.", this.watchedResource.getURI()));
// }
// //Initial SHA1 of the resource
// //TODO: currently assumes file-based resources. Think about refactoring later to support diff kinds of resources?
// final String initialSha1Hex = new Sha1Hash(this.watchedResource.getFile()).toHex();
// if (EMPTY_STRING_SHA1.equals(initialSha1Hex)) {
// logger.warn("The 'watchedResource' [{}] is empty!", this.watchedResource.getURI());
// }
// this.resourceSha1Hex = initialSha1Hex;
// }
//
// /**
// * Compare the SHA1 digests (since last check and the latest) of the configured resource, and if change is detected,
// * publish the <code>ResourceChangeEvent</code> to ApplicationContext.
// */
// public void notifyOfTheResourceChangeEventIfNecessary() {
// final String currentResourceSha1 = this.resourceSha1Hex;
// String newResourceSha1 = null;
// try {
// newResourceSha1 = new Sha1Hash(this.watchedResource.getFile()).toHex();
// if (!newResourceSha1.equals(currentResourceSha1)) {
// logger.debug("Resource: [{}] | Old Hash: [{}] | New Hash: [{}]", new Object[] {this.watchedResource.getURI(), currentResourceSha1, newResourceSha1});
// synchronized (this.resourceSha1Hex) {
// this.resourceSha1Hex = newResourceSha1;
// this.applicationEventPublisher.publishEvent(new ResourceChangedEvent(this, this.watchedResource.getURI()));
// }
// }
// }
// catch (final Throwable e) {
// //TODO: Possibly introduce an exception handling strategy?
// logger.error("An exception is caught during 'watchedResource' access", e);
// return;
// }
// }
//
// @Override
// public void setApplicationEventPublisher(final ApplicationEventPublisher applicationEventPublisher) {
// this.applicationEventPublisher = applicationEventPublisher;
// }
// }
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/JsonServiceRegistryDao.java
import com.fasterxml.jackson.databind.ObjectMapper;
import net.unicon.cas.addons.support.GuardedBy;
import net.unicon.cas.addons.support.ResourceChangeDetectingEventNotifier;
import net.unicon.cas.addons.support.ThreadSafe;
import org.jasig.cas.services.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
package net.unicon.cas.addons.serviceregistry;
/**
* Implementation of <code>ServiceRegistryDao</code> that reads services definition from JSON configuration file at the Spring Application Context
* initialization time. After un-marshaling services from JSON blob, delegates the storage and retrieval to <code>InMemoryServiceRegistryDaoImpl</code>
* <p/>
* This class implements ${link ApplicationListener<ResourceChangeDetectingEventNotifier.ResourceChangedEvent>} to reload services definitions in real-time.
* This class is thread safe.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 0.8
*/
@ThreadSafe
public class JsonServiceRegistryDao implements ServiceRegistryDao, | ApplicationListener<ResourceChangeDetectingEventNotifier.ResourceChangedEvent> { |
Unicon/cas-addons | src/test/java/net/unicon/cas/addons/config/CasNamespaceEventsRedisRecorderBeanDefinitionParserTests.java | // Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForServiceTicketValidatedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForServiceTicketValidatedEvents implements
// ApplicationListener<CasServiceTicketValidatedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForServiceTicketValidatedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForServiceTicketValidatedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasServiceTicketValidatedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:st-validated:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:st-validated:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:st-validated:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForSsoSessionEstablishedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForSsoSessionEstablishedEvents implements
// ApplicationListener<CasSsoSessionEstablishedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForSsoSessionEstablishedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForSsoSessionEstablishedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasSsoSessionEstablishedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:sso-sessions-established:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:sso-sessions-established:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:sso-sessions-established:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
| import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForServiceTicketValidatedEvents;
import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForSsoSessionEstablishedEvents;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue; | package net.unicon.cas.addons.config;
/**
* @author Dmitriy Kopylenko
* @author Unicon, inc.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CasNamespaceEventsRedisRecorderBeanDefinitionParserTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void eventsRedisRecorderBeanDefinitionCorrectlyParsed() { | // Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForServiceTicketValidatedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForServiceTicketValidatedEvents implements
// ApplicationListener<CasServiceTicketValidatedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForServiceTicketValidatedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForServiceTicketValidatedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasServiceTicketValidatedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:st-validated:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:st-validated:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:st-validated:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForSsoSessionEstablishedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForSsoSessionEstablishedEvents implements
// ApplicationListener<CasSsoSessionEstablishedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForSsoSessionEstablishedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForSsoSessionEstablishedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasSsoSessionEstablishedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:sso-sessions-established:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:sso-sessions-established:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:sso-sessions-established:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
// Path: src/test/java/net/unicon/cas/addons/config/CasNamespaceEventsRedisRecorderBeanDefinitionParserTests.java
import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForServiceTicketValidatedEvents;
import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForSsoSessionEstablishedEvents;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue;
package net.unicon.cas.addons.config;
/**
* @author Dmitriy Kopylenko
* @author Unicon, inc.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CasNamespaceEventsRedisRecorderBeanDefinitionParserTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void eventsRedisRecorderBeanDefinitionCorrectlyParsed() { | assertTrue(applicationContext.getBeansOfType(RedisStatsRecorderForSsoSessionEstablishedEvents.class).size() == 1); |
Unicon/cas-addons | src/test/java/net/unicon/cas/addons/config/CasNamespaceEventsRedisRecorderBeanDefinitionParserTests.java | // Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForServiceTicketValidatedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForServiceTicketValidatedEvents implements
// ApplicationListener<CasServiceTicketValidatedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForServiceTicketValidatedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForServiceTicketValidatedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasServiceTicketValidatedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:st-validated:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:st-validated:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:st-validated:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForSsoSessionEstablishedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForSsoSessionEstablishedEvents implements
// ApplicationListener<CasSsoSessionEstablishedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForSsoSessionEstablishedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForSsoSessionEstablishedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasSsoSessionEstablishedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:sso-sessions-established:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:sso-sessions-established:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:sso-sessions-established:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
| import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForServiceTicketValidatedEvents;
import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForSsoSessionEstablishedEvents;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue; | package net.unicon.cas.addons.config;
/**
* @author Dmitriy Kopylenko
* @author Unicon, inc.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CasNamespaceEventsRedisRecorderBeanDefinitionParserTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void eventsRedisRecorderBeanDefinitionCorrectlyParsed() {
assertTrue(applicationContext.getBeansOfType(RedisStatsRecorderForSsoSessionEstablishedEvents.class).size() == 1); | // Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForServiceTicketValidatedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForServiceTicketValidatedEvents implements
// ApplicationListener<CasServiceTicketValidatedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForServiceTicketValidatedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForServiceTicketValidatedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasServiceTicketValidatedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:st-validated:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:st-validated:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:st-validated:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForSsoSessionEstablishedEvents.java
// @ThreadSafe
// public class RedisStatsRecorderForSsoSessionEstablishedEvents implements
// ApplicationListener<CasSsoSessionEstablishedEvent> {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisStatsRecorderForSsoSessionEstablishedEvents.class);
//
// private StringRedisTemplate redisTemplate;
//
// public RedisStatsRecorderForSsoSessionEstablishedEvents(JedisConnectionFactory connectionFactory) {
// this.redisTemplate = new StringRedisTemplate(connectionFactory);
// }
//
// @Override
// public void onApplicationEvent(CasSsoSessionEstablishedEvent event) {
// final String today = DateTime.now().toString("yyyy-MM-dd");
// try {
// logger.debug("Incrementing value for key 'cas:sso-sessions-established:{}' in Redis server...", today);
// this.redisTemplate.opsForValue().increment("cas:sso-sessions-established:" + today, 1L);
// }
// catch (Throwable e) {
// logger.warn("Unable to increment value for key 'cas:sso-sessions-established:'" + today + " in Redis. Caught the following exception: ", e);
// }
// }
// }
// Path: src/test/java/net/unicon/cas/addons/config/CasNamespaceEventsRedisRecorderBeanDefinitionParserTests.java
import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForServiceTicketValidatedEvents;
import net.unicon.cas.addons.info.events.listeners.RedisStatsRecorderForSsoSessionEstablishedEvents;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue;
package net.unicon.cas.addons.config;
/**
* @author Dmitriy Kopylenko
* @author Unicon, inc.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CasNamespaceEventsRedisRecorderBeanDefinitionParserTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void eventsRedisRecorderBeanDefinitionCorrectlyParsed() {
assertTrue(applicationContext.getBeansOfType(RedisStatsRecorderForSsoSessionEstablishedEvents.class).size() == 1); | assertTrue(applicationContext.getBeansOfType(RedisStatsRecorderForServiceTicketValidatedEvents.class).size() == 1); |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/authentication/principal/StormpathPrincipalResolver.java | // Path: src/main/java/net/unicon/cas/addons/authentication/handler/StormpathAuthenticationHandler.java
// @Immutable
// public class StormpathAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {
//
// private final Application application;
//
// /**
// * Receives the Stormpath admin credentials and applicationId and sets up and instance of a Stormpath's Application resource
// * which will be used to authenticate users.
// *
// * @param stormpathAccessId accessId provided by Stormpath, for the admin user with the created API key.
// * @param stormpathSecretKey secret key provided by Stormpath, for the admin user with the created API key.
// * @param applicationId This is application id configured on Stormpath whose login source will be used to authenticate users.
// * @throws BeanCreationException If credentials cannot be verified by Stormpath.
// */
// public StormpathAuthenticationHandler(final String stormpathAccessId, final String stormpathSecretKey, final String applicationId) throws BeanCreationException {
// final Client client = new Client(new DefaultApiKey(stormpathAccessId, stormpathSecretKey));
// try {
// this.application = client.getDataStore().getResource(String.format("/applications/%s", applicationId), Application.class);
// }
// catch (Throwable e) {
// throw new BeanCreationException("An exception is caught trying to access Stormpath cloud. " +
// "Please verify that your provided Stormpath <accessId>, " +
// "<secretKey>, and <applicationId> are correct. Original Stormpath error: " + e.getMessage());
// }
// }
//
// @Override
// protected boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException {
// try {
// this.log.debug("Attempting to authenticate user [{}] against application [{}] in Stormpath cloud...", credentials.getUsername(), this.application.getName());
// this.authenticateAccount(credentials);
// this.log.debug("Successfully authenticated user [{}]", credentials.getUsername());
// return true;
// }
// catch (ResourceException e) {
// this.log.error(e.getMessage(), e);
// throw new BadCredentialsAuthenticationException();
// }
// }
//
// public Account authenticateAccount(final UsernamePasswordCredentials credentials) throws ResourceException {
// return this.application.authenticateAccount(new UsernamePasswordRequest(credentials.getUsername(), credentials.getPassword())).getAccount();
// }
// }
| import com.stormpath.sdk.account.Account;
import com.stormpath.sdk.resource.ResourceException;
import net.unicon.cas.addons.authentication.handler.StormpathAuthenticationHandler;
import net.unicon.cas.addons.support.ThreadSafe;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package net.unicon.cas.addons.authentication.principal;
/**
* An implementation of {@link org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver}
* that resolves instances of {@link StormpathPrincipal} from provided {@link org.jasig.cas.authentication.principal.UsernamePasswordCredentials}
* <p/>
* Note that this implementation makes a remote HTTP call to Stormapth cloud to authenticate the credential and therefore
* retrieve an instance of an {@link com.stormpath.sdk.account.Account}. Thus, 2 Stormpath remote authentication calls are made -
* one is during authentication by {@link net.unicon.cas.addons.authentication.handler.StormpathAuthenticationHandler} and
* one is during <code>Account</code> retrieval by this class.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.4
*/
@ThreadSafe
public class StormpathPrincipalResolver implements CredentialsToPrincipalResolver {
| // Path: src/main/java/net/unicon/cas/addons/authentication/handler/StormpathAuthenticationHandler.java
// @Immutable
// public class StormpathAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {
//
// private final Application application;
//
// /**
// * Receives the Stormpath admin credentials and applicationId and sets up and instance of a Stormpath's Application resource
// * which will be used to authenticate users.
// *
// * @param stormpathAccessId accessId provided by Stormpath, for the admin user with the created API key.
// * @param stormpathSecretKey secret key provided by Stormpath, for the admin user with the created API key.
// * @param applicationId This is application id configured on Stormpath whose login source will be used to authenticate users.
// * @throws BeanCreationException If credentials cannot be verified by Stormpath.
// */
// public StormpathAuthenticationHandler(final String stormpathAccessId, final String stormpathSecretKey, final String applicationId) throws BeanCreationException {
// final Client client = new Client(new DefaultApiKey(stormpathAccessId, stormpathSecretKey));
// try {
// this.application = client.getDataStore().getResource(String.format("/applications/%s", applicationId), Application.class);
// }
// catch (Throwable e) {
// throw new BeanCreationException("An exception is caught trying to access Stormpath cloud. " +
// "Please verify that your provided Stormpath <accessId>, " +
// "<secretKey>, and <applicationId> are correct. Original Stormpath error: " + e.getMessage());
// }
// }
//
// @Override
// protected boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException {
// try {
// this.log.debug("Attempting to authenticate user [{}] against application [{}] in Stormpath cloud...", credentials.getUsername(), this.application.getName());
// this.authenticateAccount(credentials);
// this.log.debug("Successfully authenticated user [{}]", credentials.getUsername());
// return true;
// }
// catch (ResourceException e) {
// this.log.error(e.getMessage(), e);
// throw new BadCredentialsAuthenticationException();
// }
// }
//
// public Account authenticateAccount(final UsernamePasswordCredentials credentials) throws ResourceException {
// return this.application.authenticateAccount(new UsernamePasswordRequest(credentials.getUsername(), credentials.getPassword())).getAccount();
// }
// }
// Path: src/main/java/net/unicon/cas/addons/authentication/principal/StormpathPrincipalResolver.java
import com.stormpath.sdk.account.Account;
import com.stormpath.sdk.resource.ResourceException;
import net.unicon.cas.addons.authentication.handler.StormpathAuthenticationHandler;
import net.unicon.cas.addons.support.ThreadSafe;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package net.unicon.cas.addons.authentication.principal;
/**
* An implementation of {@link org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver}
* that resolves instances of {@link StormpathPrincipal} from provided {@link org.jasig.cas.authentication.principal.UsernamePasswordCredentials}
* <p/>
* Note that this implementation makes a remote HTTP call to Stormapth cloud to authenticate the credential and therefore
* retrieve an instance of an {@link com.stormpath.sdk.account.Account}. Thus, 2 Stormpath remote authentication calls are made -
* one is during authentication by {@link net.unicon.cas.addons.authentication.handler.StormpathAuthenticationHandler} and
* one is during <code>Account</code> retrieval by this class.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.4
*/
@ThreadSafe
public class StormpathPrincipalResolver implements CredentialsToPrincipalResolver {
| private final StormpathAuthenticationHandler stormpathAuthenticationHandler; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/authentication/handler/EmailAddressToPrincipalNameTransformer.java | // Path: src/main/java/net/unicon/cas/addons/authentication/principal/util/PrincipalUtils.java
// public final class PrincipalUtils {
//
// /**
// * Parses the <code>username</code> and transforms it back if the value is recognized as en email address.
// * Otherwise, returns the original value.
// *
// * @param username username or email address of the principal passed. A valid email address would be in the format of
// * "[email protected]"
// * @return Transformed <code>username</code> or <code>null</code> if <code>username</code> is <code>null</code> or blank.
// */
// public static String parseNamePartFromEmailAddressIfNecessary(final String username) {
// if (StringUtils.isBlank(username)) {
// return null;
// }
//
// final int idx = username.indexOf('@');
// if (idx == -1) {
// return username;
// }
// return username.substring(0, idx);
// }
//
// }
| import net.unicon.cas.addons.authentication.principal.util.PrincipalUtils;
import org.jasig.cas.authentication.handler.PrincipalNameTransformer; | package net.unicon.cas.addons.authentication.handler;
/**
* An implementation of the {@link PrincipalNameTransformer} that accepts an email address
* and transforms it back to the user id.
*
* <p>Note: this API is only intended to be called by CAS server code e.g. any custom CAS server overlay extension, etc.</p>
*
* @author <a href="mailto:[email protected]">Misagh Moayyed</a>
* @author Unicon, inc.
* @since 0.6
*/
public class EmailAddressToPrincipalNameTransformer implements PrincipalNameTransformer {
@Override
public String transform(final String principalId) { | // Path: src/main/java/net/unicon/cas/addons/authentication/principal/util/PrincipalUtils.java
// public final class PrincipalUtils {
//
// /**
// * Parses the <code>username</code> and transforms it back if the value is recognized as en email address.
// * Otherwise, returns the original value.
// *
// * @param username username or email address of the principal passed. A valid email address would be in the format of
// * "[email protected]"
// * @return Transformed <code>username</code> or <code>null</code> if <code>username</code> is <code>null</code> or blank.
// */
// public static String parseNamePartFromEmailAddressIfNecessary(final String username) {
// if (StringUtils.isBlank(username)) {
// return null;
// }
//
// final int idx = username.indexOf('@');
// if (idx == -1) {
// return username;
// }
// return username.substring(0, idx);
// }
//
// }
// Path: src/main/java/net/unicon/cas/addons/authentication/handler/EmailAddressToPrincipalNameTransformer.java
import net.unicon.cas.addons.authentication.principal.util.PrincipalUtils;
import org.jasig.cas.authentication.handler.PrincipalNameTransformer;
package net.unicon.cas.addons.authentication.handler;
/**
* An implementation of the {@link PrincipalNameTransformer} that accepts an email address
* and transforms it back to the user id.
*
* <p>Note: this API is only intended to be called by CAS server code e.g. any custom CAS server overlay extension, etc.</p>
*
* @author <a href="mailto:[email protected]">Misagh Moayyed</a>
* @author Unicon, inc.
* @since 0.6
*/
public class EmailAddressToPrincipalNameTransformer implements PrincipalNameTransformer {
@Override
public String transform(final String principalId) { | return PrincipalUtils.parseNamePartFromEmailAddressIfNecessary(principalId); |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/web/support/ServiceInitiatingWebSsoAwareCookieGenerator.java | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
| import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List; | package net.unicon.cas.addons.web.support;
/**
* Specialization of <code>CookieRetrievingCookieGenerator</code> that decides whether to generate or not CAS TGC
* based on a particular service's configuration setting for web SSO initiation.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.2
*/
public class ServiceInitiatingWebSsoAwareCookieGenerator extends CookieRetrievingCookieGenerator implements
InitializingBean {
private ServicesManager servicesManager;
private List<ArgumentExtractor> argumentExtractors;
| // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
// Path: src/main/java/net/unicon/cas/addons/web/support/ServiceInitiatingWebSsoAwareCookieGenerator.java
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
package net.unicon.cas.addons.web.support;
/**
* Specialization of <code>CookieRetrievingCookieGenerator</code> that decides whether to generate or not CAS TGC
* based on a particular service's configuration setting for web SSO initiation.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.2
*/
public class ServiceInitiatingWebSsoAwareCookieGenerator extends CookieRetrievingCookieGenerator implements
InitializingBean {
private ServicesManager servicesManager;
private List<ArgumentExtractor> argumentExtractors;
| private RegisteredServicesPolicies registeredServicesPolicies; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/web/support/ServiceInitiatingWebSsoAwareCookieGenerator.java | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
| import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List; | package net.unicon.cas.addons.web.support;
/**
* Specialization of <code>CookieRetrievingCookieGenerator</code> that decides whether to generate or not CAS TGC
* based on a particular service's configuration setting for web SSO initiation.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.2
*/
public class ServiceInitiatingWebSsoAwareCookieGenerator extends CookieRetrievingCookieGenerator implements
InitializingBean {
private ServicesManager servicesManager;
private List<ArgumentExtractor> argumentExtractors;
private RegisteredServicesPolicies registeredServicesPolicies;
public void setServicesManager(ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
public void setArgumentExtractors(List<ArgumentExtractor> argumentExtractors) {
this.argumentExtractors = argumentExtractors;
}
public void setRegisteredServicesPolicies(RegisteredServicesPolicies registeredServicesPolicies) {
this.registeredServicesPolicies = registeredServicesPolicies;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.servicesManager, "servicesManager is required.");
Assert.notNull(this.argumentExtractors, "argumentsExtractors are required.");
Assert.notNull(this.registeredServicesPolicies, "registeredServicesPolicies is required.");
}
@Override
public void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieValue) { | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
// Path: src/main/java/net/unicon/cas/addons/web/support/ServiceInitiatingWebSsoAwareCookieGenerator.java
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
package net.unicon.cas.addons.web.support;
/**
* Specialization of <code>CookieRetrievingCookieGenerator</code> that decides whether to generate or not CAS TGC
* based on a particular service's configuration setting for web SSO initiation.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.2
*/
public class ServiceInitiatingWebSsoAwareCookieGenerator extends CookieRetrievingCookieGenerator implements
InitializingBean {
private ServicesManager servicesManager;
private List<ArgumentExtractor> argumentExtractors;
private RegisteredServicesPolicies registeredServicesPolicies;
public void setServicesManager(ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
public void setArgumentExtractors(List<ArgumentExtractor> argumentExtractors) {
this.argumentExtractors = argumentExtractors;
}
public void setRegisteredServicesPolicies(RegisteredServicesPolicies registeredServicesPolicies) {
this.registeredServicesPolicies = registeredServicesPolicies;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.servicesManager, "servicesManager is required.");
Assert.notNull(this.argumentExtractors, "argumentsExtractors are required.");
Assert.notNull(this.registeredServicesPolicies, "registeredServicesPolicies is required.");
}
@Override
public void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieValue) { | RegisteredServiceWithAttributes registeredService = |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/authentication/principal/EmailAddressPasswordCredentialsToPrincipalResolver.java | // Path: src/main/java/net/unicon/cas/addons/authentication/principal/util/PrincipalUtils.java
// public final class PrincipalUtils {
//
// /**
// * Parses the <code>username</code> and transforms it back if the value is recognized as en email address.
// * Otherwise, returns the original value.
// *
// * @param username username or email address of the principal passed. A valid email address would be in the format of
// * "[email protected]"
// * @return Transformed <code>username</code> or <code>null</code> if <code>username</code> is <code>null</code> or blank.
// */
// public static String parseNamePartFromEmailAddressIfNecessary(final String username) {
// if (StringUtils.isBlank(username)) {
// return null;
// }
//
// final int idx = username.indexOf('@');
// if (idx == -1) {
// return username;
// }
// return username.substring(0, idx);
// }
//
// }
| import net.unicon.cas.addons.authentication.principal.util.PrincipalUtils;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.authentication.principal.AbstractPersonDirectoryCredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials; | package net.unicon.cas.addons.authentication.principal;
/**
* An implementation of the {@link AbstractPersonDirectoryCredentialsToPrincipalResolver} that accepts an email address
* as the {@link UsernamePasswordCredentials}'s username and resolves it back to the user id.
* <p>Note: this API is only intended to be called by CAS server code e.g. any custom CAS server overlay extension, etc.</p>
*
* @author <a href="mailto:[email protected]">Misagh Moayyed</a>
* @author Unicon, inc.
* @since 0.6
*/
public class EmailAddressPasswordCredentialsToPrincipalResolver extends AbstractPersonDirectoryCredentialsToPrincipalResolver {
@Override
public boolean supports(final Credentials credentials) {
return credentials != null && UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass());
}
@Override
protected String extractPrincipalId(final Credentials credentials) {
if (credentials == null) {
return null;
}
final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
if (StringUtils.isBlank(usernamePasswordCredentials.getUsername())) {
return null;
}
| // Path: src/main/java/net/unicon/cas/addons/authentication/principal/util/PrincipalUtils.java
// public final class PrincipalUtils {
//
// /**
// * Parses the <code>username</code> and transforms it back if the value is recognized as en email address.
// * Otherwise, returns the original value.
// *
// * @param username username or email address of the principal passed. A valid email address would be in the format of
// * "[email protected]"
// * @return Transformed <code>username</code> or <code>null</code> if <code>username</code> is <code>null</code> or blank.
// */
// public static String parseNamePartFromEmailAddressIfNecessary(final String username) {
// if (StringUtils.isBlank(username)) {
// return null;
// }
//
// final int idx = username.indexOf('@');
// if (idx == -1) {
// return username;
// }
// return username.substring(0, idx);
// }
//
// }
// Path: src/main/java/net/unicon/cas/addons/authentication/principal/EmailAddressPasswordCredentialsToPrincipalResolver.java
import net.unicon.cas.addons.authentication.principal.util.PrincipalUtils;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.authentication.principal.AbstractPersonDirectoryCredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
package net.unicon.cas.addons.authentication.principal;
/**
* An implementation of the {@link AbstractPersonDirectoryCredentialsToPrincipalResolver} that accepts an email address
* as the {@link UsernamePasswordCredentials}'s username and resolves it back to the user id.
* <p>Note: this API is only intended to be called by CAS server code e.g. any custom CAS server overlay extension, etc.</p>
*
* @author <a href="mailto:[email protected]">Misagh Moayyed</a>
* @author Unicon, inc.
* @since 0.6
*/
public class EmailAddressPasswordCredentialsToPrincipalResolver extends AbstractPersonDirectoryCredentialsToPrincipalResolver {
@Override
public boolean supports(final Credentials credentials) {
return credentials != null && UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass());
}
@Override
protected String extractPrincipalId(final Credentials credentials) {
if (credentials == null) {
return null;
}
final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
if (StringUtils.isBlank(usernamePasswordCredentials.getUsername())) {
return null;
}
| return PrincipalUtils.parseNamePartFromEmailAddressIfNecessary(usernamePasswordCredentials.getUsername()); |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/events/CentralAuthenticationServiceEventsPublishingAspect.java | // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
| import net.unicon.cas.addons.authentication.AuthenticationSupport;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware; | package net.unicon.cas.addons.info.events;
/**
* Aspect implementing a mechanism by which to intercept core CAS runtime events and publish them as Spring <code>ApplicationEvent</code>s
* to <code>ApplicationContext</code> in which CAS server is deployed for further consumption by any number of registered <code>ApplicationListener</code>s.
* <p/>
* The events published by this aspect are {@link CasSsoSessionEstablishedEvent}, {@link CasSsoSessionDestroyedEvent}, {@link CasServiceTicketGrantedEvent}, {@link CasServiceTicketValidatedEvent}
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.1
*/
@Aspect
public class CentralAuthenticationServiceEventsPublishingAspect implements ApplicationEventPublisherAware {
private ApplicationEventPublisher eventPublisher;
| // Path: src/main/java/net/unicon/cas/addons/authentication/AuthenticationSupport.java
// public interface AuthenticationSupport {
//
// /**
// * Retrieve a valid Authentication object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested Authentication
// * @return valid Authentication OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Authentication getAuthenticationFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal object identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal
// * @return valid Principal OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Principal getAuthenticatedPrincipalFrom(String ticketGrantingTicketId) throws RuntimeException;
//
// /**
// * Retrieve a valid Principal's map of attributes identified by the provided TGT SSO token
// * @param ticketGrantingTicketId an SSO token identifying the requested authenticated Principal's attributes
// * @return valid Principal's attributes OR <b>NULL</b> if there is no valid SSO session present identified by the provided TGT id SSO token
// * @throws RuntimeException
// */
// Map<String, Object> getPrincipalAttributesFrom(String ticketGrantingTicketId) throws RuntimeException;
// }
// Path: src/main/java/net/unicon/cas/addons/info/events/CentralAuthenticationServiceEventsPublishingAspect.java
import net.unicon.cas.addons.authentication.AuthenticationSupport;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
package net.unicon.cas.addons.info.events;
/**
* Aspect implementing a mechanism by which to intercept core CAS runtime events and publish them as Spring <code>ApplicationEvent</code>s
* to <code>ApplicationContext</code> in which CAS server is deployed for further consumption by any number of registered <code>ApplicationListener</code>s.
* <p/>
* The events published by this aspect are {@link CasSsoSessionEstablishedEvent}, {@link CasSsoSessionDestroyedEvent}, {@link CasServiceTicketGrantedEvent}, {@link CasServiceTicketValidatedEvent}
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.1
*/
@Aspect
public class CentralAuthenticationServiceEventsPublishingAspect implements ApplicationEventPublisherAware {
private ApplicationEventPublisher eventPublisher;
| private final AuthenticationSupport authenticationSupport; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForSsoSessionEstablishedEvents.java | // Path: src/main/java/net/unicon/cas/addons/info/events/CasSsoSessionEstablishedEvent.java
// public final class CasSsoSessionEstablishedEvent extends AbstractCasSsoEvent {
//
// public CasSsoSessionEstablishedEvent(Object source, Authentication authentication, String ticketGrantingTicketId) {
// super(source, authentication, ticketGrantingTicketId);
// }
// }
| import net.unicon.cas.addons.info.events.CasSsoSessionEstablishedEvent;
import net.unicon.cas.addons.support.ThreadSafe;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate; | package net.unicon.cas.addons.info.events.listeners;
/**
* An event listener for <code>CasSsoSessionEstablishedEvent</code>s that records daily counts for each event by atomically incrementing a value in
* Redis server under a <i>cas:sso-sessions-established:yyyy-MM-dd</i> key.
* <p/>
* This class assumes a live Redis server running and depends on an instance of <code>org.springframework.data.redis.connection.jedis.JedisConnectionFactory</code>
* of spring data redis module, from which it constructs an instance of <code>org.springframework.data.redis.core.StringRedisTemplate</code>.
* <p/>
* At runtime if a Redis server becomes unavailable or any other exceptions are thrown during server access, a WARN level log message logs the exception and execution path
* of CAS server continues.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.9
*/
@ThreadSafe
public class RedisStatsRecorderForSsoSessionEstablishedEvents implements | // Path: src/main/java/net/unicon/cas/addons/info/events/CasSsoSessionEstablishedEvent.java
// public final class CasSsoSessionEstablishedEvent extends AbstractCasSsoEvent {
//
// public CasSsoSessionEstablishedEvent(Object source, Authentication authentication, String ticketGrantingTicketId) {
// super(source, authentication, ticketGrantingTicketId);
// }
// }
// Path: src/main/java/net/unicon/cas/addons/info/events/listeners/RedisStatsRecorderForSsoSessionEstablishedEvents.java
import net.unicon.cas.addons.info.events.CasSsoSessionEstablishedEvent;
import net.unicon.cas.addons.support.ThreadSafe;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
package net.unicon.cas.addons.info.events.listeners;
/**
* An event listener for <code>CasSsoSessionEstablishedEvent</code>s that records daily counts for each event by atomically incrementing a value in
* Redis server under a <i>cas:sso-sessions-established:yyyy-MM-dd</i> key.
* <p/>
* This class assumes a live Redis server running and depends on an instance of <code>org.springframework.data.redis.connection.jedis.JedisConnectionFactory</code>
* of spring data redis module, from which it constructs an instance of <code>org.springframework.data.redis.core.StringRedisTemplate</code>.
* <p/>
* At runtime if a Redis server becomes unavailable or any other exceptions are thrown during server access, a WARN level log message logs the exception and execution path
* of CAS server continues.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.9
*/
@ThreadSafe
public class RedisStatsRecorderForSsoSessionEstablishedEvents implements | ApplicationListener<CasSsoSessionEstablishedEvent> { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/serviceregistry/services/internal/DefaultRegisteredServicesPolicies.java | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
| import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies; | package net.unicon.cas.addons.serviceregistry.services.internal;
/**
* Default implementation of <code>RegisteredServicesPolicies</code>
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.2
*/
public class DefaultRegisteredServicesPolicies implements RegisteredServicesPolicies {
public static final String SSO_INITIATION_ATTRIBUTE_KEY = "initiateSSO";
@Override | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/internal/DefaultRegisteredServicesPolicies.java
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
package net.unicon.cas.addons.serviceregistry.services.internal;
/**
* Default implementation of <code>RegisteredServicesPolicies</code>
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.2
*/
public class DefaultRegisteredServicesPolicies implements RegisteredServicesPolicies {
public static final String SSO_INITIATION_ATTRIBUTE_KEY = "initiateSSO";
@Override | public boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService) { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/web/support/SsoDestroyingServiceValidateController.java | // Path: src/main/java/net/unicon/cas/addons/authentication/support/Assertions.java
// public final class Assertions {
//
// /**
// * Non-instantiable
// */
// private Assertions() {
// }
//
// /**
// * Extracts an authenticated ${@link Principal} from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve ${@link Principal} from
// * @return Authenticated Principal
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static Principal getAuthenticatedPrincipalFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final Principal principal = chain.get(chain.size() - 1).getPrincipal();
// return principal;
// }
//
// /**
// * Extracts a list of proxy ${@link Authentication}s MINUS the original authenticated ${@link Principal} f
// * from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve a list of proxy ${@link Authentication}s from
// * @return A list of proxy authentications
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static List<Authentication> getProxyAuthenticationsFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final List<Authentication> proxyAuthentications = chain.subList(0, chain.size()-1);
// return proxyAuthentications;
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
| import net.unicon.cas.addons.authentication.support.Assertions;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.web.ServiceValidateController;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | package net.unicon.cas.addons.web.support;
/**
* An extention of a <code>ServiceValidateController</code> that destroys server-side TGT upon successful Service Ticket validation.
* <p/>
* Useful for services that are configured not to initiate WebSSO sessions altogether.
*
* @author Dmitriy Kopylenko,
* @author Unicon, inc.
* @since 1.2
*/
public class SsoDestroyingServiceValidateController extends ServiceValidateController implements InitializingBean {
private TicketRegistry ticketRegistry;
private CentralAuthenticationService cas;
private ServicesManager servicesManager;
private ArgumentExtractor argExtractor;
| // Path: src/main/java/net/unicon/cas/addons/authentication/support/Assertions.java
// public final class Assertions {
//
// /**
// * Non-instantiable
// */
// private Assertions() {
// }
//
// /**
// * Extracts an authenticated ${@link Principal} from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve ${@link Principal} from
// * @return Authenticated Principal
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static Principal getAuthenticatedPrincipalFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final Principal principal = chain.get(chain.size() - 1).getPrincipal();
// return principal;
// }
//
// /**
// * Extracts a list of proxy ${@link Authentication}s MINUS the original authenticated ${@link Principal} f
// * from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve a list of proxy ${@link Authentication}s from
// * @return A list of proxy authentications
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static List<Authentication> getProxyAuthenticationsFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final List<Authentication> proxyAuthentications = chain.subList(0, chain.size()-1);
// return proxyAuthentications;
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
// Path: src/main/java/net/unicon/cas/addons/web/support/SsoDestroyingServiceValidateController.java
import net.unicon.cas.addons.authentication.support.Assertions;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.web.ServiceValidateController;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
package net.unicon.cas.addons.web.support;
/**
* An extention of a <code>ServiceValidateController</code> that destroys server-side TGT upon successful Service Ticket validation.
* <p/>
* Useful for services that are configured not to initiate WebSSO sessions altogether.
*
* @author Dmitriy Kopylenko,
* @author Unicon, inc.
* @since 1.2
*/
public class SsoDestroyingServiceValidateController extends ServiceValidateController implements InitializingBean {
private TicketRegistry ticketRegistry;
private CentralAuthenticationService cas;
private ServicesManager servicesManager;
private ArgumentExtractor argExtractor;
| private RegisteredServicesPolicies registeredServicesPolicies; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/web/support/SsoDestroyingServiceValidateController.java | // Path: src/main/java/net/unicon/cas/addons/authentication/support/Assertions.java
// public final class Assertions {
//
// /**
// * Non-instantiable
// */
// private Assertions() {
// }
//
// /**
// * Extracts an authenticated ${@link Principal} from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve ${@link Principal} from
// * @return Authenticated Principal
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static Principal getAuthenticatedPrincipalFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final Principal principal = chain.get(chain.size() - 1).getPrincipal();
// return principal;
// }
//
// /**
// * Extracts a list of proxy ${@link Authentication}s MINUS the original authenticated ${@link Principal} f
// * from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve a list of proxy ${@link Authentication}s from
// * @return A list of proxy authentications
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static List<Authentication> getProxyAuthenticationsFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final List<Authentication> proxyAuthentications = chain.subList(0, chain.size()-1);
// return proxyAuthentications;
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
| import net.unicon.cas.addons.authentication.support.Assertions;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.web.ServiceValidateController;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | this.registeredServicesPolicies = registeredServicesPolicies;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.ticketRegistry, "ticketRegistry is required");
Assert.notNull(this.cas, "cas is required");
Assert.notNull(this.servicesManager, "servicesManager is required");
Assert.notNull(this.argExtractor, "argExtractor is required");
Assert.notNull(this.registeredServicesPolicies, "registeredServicesPolicies is required");
}
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
final WebApplicationService service = this.argExtractor.extractService(request);
if (service == null) {
return super.handleRequest(request, response);
}
Ticket st = this.ticketRegistry.getTicket(service.getArtifactId());
if (st == null) {
return super.handleRequest(request, response);
}
//Make the tgt available in ThreadLocal for access in "onSuccessfulValidation()"
tgtHolder.set(st.getGrantingTicket());
return super.handleRequest(request, response);
}
@Override
protected void onSuccessfulValidation(String serviceTicketId, Assertion assertion) {
try { | // Path: src/main/java/net/unicon/cas/addons/authentication/support/Assertions.java
// public final class Assertions {
//
// /**
// * Non-instantiable
// */
// private Assertions() {
// }
//
// /**
// * Extracts an authenticated ${@link Principal} from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve ${@link Principal} from
// * @return Authenticated Principal
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static Principal getAuthenticatedPrincipalFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final Principal principal = chain.get(chain.size() - 1).getPrincipal();
// return principal;
// }
//
// /**
// * Extracts a list of proxy ${@link Authentication}s MINUS the original authenticated ${@link Principal} f
// * from a provided ${@link Assertion} instance.
// * <p/>
// * It is a caller's of this method responsibility to ensure that provided ${@link Assertion} instance is not null
// * to avoid NPE at runtime.
// *
// * @param assertion instance to retrieve a list of proxy ${@link Authentication}s from
// * @return A list of proxy authentications
// * @throws NullPointerException if provided Assertion is <i>null</i>
// */
// public static List<Authentication> getProxyAuthenticationsFrom(Assertion assertion) {
// final List<Authentication> chain = assertion.getChainedAuthentications();
// final List<Authentication> proxyAuthentications = chain.subList(0, chain.size()-1);
// return proxyAuthentications;
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/serviceregistry/services/RegisteredServicesPolicies.java
// public interface RegisteredServicesPolicies {
//
// /**
// * Policy method governing WebSSO session initiation based on the provided configuration attributes of a given
// * <code>RegisteredServiceWithAttributes</code>
// *
// * @param registeredService for which to determine whether to initiate an SSO session or not
// * @return true if a provided service is eligible for an SSO session initiation, false otherwise
// */
// boolean ssoSessionInitiating(RegisteredServiceWithAttributes registeredService);
// }
// Path: src/main/java/net/unicon/cas/addons/web/support/SsoDestroyingServiceValidateController.java
import net.unicon.cas.addons.authentication.support.Assertions;
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import net.unicon.cas.addons.serviceregistry.services.RegisteredServicesPolicies;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.web.ServiceValidateController;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
this.registeredServicesPolicies = registeredServicesPolicies;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.ticketRegistry, "ticketRegistry is required");
Assert.notNull(this.cas, "cas is required");
Assert.notNull(this.servicesManager, "servicesManager is required");
Assert.notNull(this.argExtractor, "argExtractor is required");
Assert.notNull(this.registeredServicesPolicies, "registeredServicesPolicies is required");
}
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
final WebApplicationService service = this.argExtractor.extractService(request);
if (service == null) {
return super.handleRequest(request, response);
}
Ticket st = this.ticketRegistry.getTicket(service.getArtifactId());
if (st == null) {
return super.handleRequest(request, response);
}
//Make the tgt available in ThreadLocal for access in "onSuccessfulValidation()"
tgtHolder.set(st.getGrantingTicket());
return super.handleRequest(request, response);
}
@Override
protected void onSuccessfulValidation(String serviceTicketId, Assertion assertion) {
try { | RegisteredServiceWithAttributes registeredService = |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/internal/DefaultSingleSignOnSessionsReport.java | // Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
// public interface SingleSignOnSessionsReport {
//
//
// enum SsoSessionAttributeKeys {
//
// AUTHENTICATED_PRINCIPAL("authenticated_principal"),
//
// AUTHENTICATION_DATE("authentication_date"),
//
// NUMBER_OF_USES("number_of_uses");
//
// private String attributeKey;
//
// private SsoSessionAttributeKeys(String attributeKey) {
// this.attributeKey = attributeKey;
// }
//
// @Override
// public String toString() {
// return this.attributeKey;
// }
// }
//
// /**
// * Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
// * <p/>
// * If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
// *
// * @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
// * no active SSO sessions
// */
// Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException;
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
| import net.unicon.cas.addons.info.SingleSignOnSessionsReport;
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*; | package net.unicon.cas.addons.info.internal;
/**
* Default implementation of <code>SingleSignOnSessionReport</code>
* <p/>
* Uses CAS' <code>TicketSupport</code> API to retrieve <code>TicketGrantingTicket</code>s
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component | // Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
// public interface SingleSignOnSessionsReport {
//
//
// enum SsoSessionAttributeKeys {
//
// AUTHENTICATED_PRINCIPAL("authenticated_principal"),
//
// AUTHENTICATION_DATE("authentication_date"),
//
// NUMBER_OF_USES("number_of_uses");
//
// private String attributeKey;
//
// private SsoSessionAttributeKeys(String attributeKey) {
// this.attributeKey = attributeKey;
// }
//
// @Override
// public String toString() {
// return this.attributeKey;
// }
// }
//
// /**
// * Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
// * <p/>
// * If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
// *
// * @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
// * no active SSO sessions
// */
// Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException;
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
// Path: src/main/java/net/unicon/cas/addons/info/internal/DefaultSingleSignOnSessionsReport.java
import net.unicon.cas.addons.info.SingleSignOnSessionsReport;
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
package net.unicon.cas.addons.info.internal;
/**
* Default implementation of <code>SingleSignOnSessionReport</code>
* <p/>
* Uses CAS' <code>TicketSupport</code> API to retrieve <code>TicketGrantingTicket</code>s
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component | public class DefaultSingleSignOnSessionsReport implements SingleSignOnSessionsReport { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/internal/DefaultSingleSignOnSessionsReport.java | // Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
// public interface SingleSignOnSessionsReport {
//
//
// enum SsoSessionAttributeKeys {
//
// AUTHENTICATED_PRINCIPAL("authenticated_principal"),
//
// AUTHENTICATION_DATE("authentication_date"),
//
// NUMBER_OF_USES("number_of_uses");
//
// private String attributeKey;
//
// private SsoSessionAttributeKeys(String attributeKey) {
// this.attributeKey = attributeKey;
// }
//
// @Override
// public String toString() {
// return this.attributeKey;
// }
// }
//
// /**
// * Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
// * <p/>
// * If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
// *
// * @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
// * no active SSO sessions
// */
// Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException;
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
| import net.unicon.cas.addons.info.SingleSignOnSessionsReport;
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*; | package net.unicon.cas.addons.info.internal;
/**
* Default implementation of <code>SingleSignOnSessionReport</code>
* <p/>
* Uses CAS' <code>TicketSupport</code> API to retrieve <code>TicketGrantingTicket</code>s
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component
public class DefaultSingleSignOnSessionsReport implements SingleSignOnSessionsReport {
| // Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
// public interface SingleSignOnSessionsReport {
//
//
// enum SsoSessionAttributeKeys {
//
// AUTHENTICATED_PRINCIPAL("authenticated_principal"),
//
// AUTHENTICATION_DATE("authentication_date"),
//
// NUMBER_OF_USES("number_of_uses");
//
// private String attributeKey;
//
// private SsoSessionAttributeKeys(String attributeKey) {
// this.attributeKey = attributeKey;
// }
//
// @Override
// public String toString() {
// return this.attributeKey;
// }
// }
//
// /**
// * Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
// * <p/>
// * If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
// *
// * @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
// * no active SSO sessions
// */
// Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException;
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
// Path: src/main/java/net/unicon/cas/addons/info/internal/DefaultSingleSignOnSessionsReport.java
import net.unicon.cas.addons.info.SingleSignOnSessionsReport;
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
package net.unicon.cas.addons.info.internal;
/**
* Default implementation of <code>SingleSignOnSessionReport</code>
* <p/>
* Uses CAS' <code>TicketSupport</code> API to retrieve <code>TicketGrantingTicket</code>s
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component
public class DefaultSingleSignOnSessionsReport implements SingleSignOnSessionsReport {
| private final TicketSupport ticketSupport; |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/internal/DefaultSingleSignOnSessionsReport.java | // Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
// public interface SingleSignOnSessionsReport {
//
//
// enum SsoSessionAttributeKeys {
//
// AUTHENTICATED_PRINCIPAL("authenticated_principal"),
//
// AUTHENTICATION_DATE("authentication_date"),
//
// NUMBER_OF_USES("number_of_uses");
//
// private String attributeKey;
//
// private SsoSessionAttributeKeys(String attributeKey) {
// this.attributeKey = attributeKey;
// }
//
// @Override
// public String toString() {
// return this.attributeKey;
// }
// }
//
// /**
// * Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
// * <p/>
// * If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
// *
// * @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
// * no active SSO sessions
// */
// Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException;
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
| import net.unicon.cas.addons.info.SingleSignOnSessionsReport;
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*; | package net.unicon.cas.addons.info.internal;
/**
* Default implementation of <code>SingleSignOnSessionReport</code>
* <p/>
* Uses CAS' <code>TicketSupport</code> API to retrieve <code>TicketGrantingTicket</code>s
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component
public class DefaultSingleSignOnSessionsReport implements SingleSignOnSessionsReport {
private final TicketSupport ticketSupport;
@Autowired
public DefaultSingleSignOnSessionsReport(TicketSupport ticketSupport) {
this.ticketSupport = ticketSupport;
}
@Override | // Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReport.java
// public interface SingleSignOnSessionsReport {
//
//
// enum SsoSessionAttributeKeys {
//
// AUTHENTICATED_PRINCIPAL("authenticated_principal"),
//
// AUTHENTICATION_DATE("authentication_date"),
//
// NUMBER_OF_USES("number_of_uses");
//
// private String attributeKey;
//
// private SsoSessionAttributeKeys(String attributeKey) {
// this.attributeKey = attributeKey;
// }
//
// @Override
// public String toString() {
// return this.attributeKey;
// }
// }
//
// /**
// * Get a collection of active (unexpired) CAS' SSO sessions (with their associated authentication and metadata).
// * <p/>
// * If there are no active SSO session, return an empty Collection and never return <strong>null</strong>
// *
// * @return a collection of SSO sessions (represented by Map of its attributes) OR and empty collection if there are
// * no active SSO sessions
// */
// Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException;
//
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
// Path: src/main/java/net/unicon/cas/addons/info/internal/DefaultSingleSignOnSessionsReport.java
import net.unicon.cas.addons.info.SingleSignOnSessionsReport;
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
package net.unicon.cas.addons.info.internal;
/**
* Default implementation of <code>SingleSignOnSessionReport</code>
* <p/>
* Uses CAS' <code>TicketSupport</code> API to retrieve <code>TicketGrantingTicket</code>s
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component
public class DefaultSingleSignOnSessionsReport implements SingleSignOnSessionsReport {
private final TicketSupport ticketSupport;
@Autowired
public DefaultSingleSignOnSessionsReport(TicketSupport ticketSupport) {
this.ticketSupport = ticketSupport;
}
@Override | public Collection<Map<String, Object>> getActiveSsoSessions() throws BulkRetrievalOfTicketsNotSupportedException { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReportResource.java | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map; | package net.unicon.cas.addons.info;
/**
* RESTful HTTP resource to expose <code>SingleSignOnSessionsReport</code> as <i>application/json</i> media type.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@Component
@Path("/")
public class SingleSignOnSessionsReportResource {
private final SingleSignOnSessionsReport singleSignOnSessionsReport;
private final ObjectMapper jsonMapper = new ObjectMapper();
private static final String ROOT_REPORT_ACTIVE_SESSIONS_KEY = "activeSsoSessions";
private static final String ROOT_REPORT_NA_KEY = "notAvailable";
private static final Logger logger = LoggerFactory.getLogger(SingleSignOnSessionsReportResource.class);
@Autowired
public SingleSignOnSessionsReportResource(SingleSignOnSessionsReport singleSignOnSessionsReport) {
this.singleSignOnSessionsReport = singleSignOnSessionsReport;
//Configure mapper strategies
this.jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
this.jsonMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response showActiveSsoSessions() {
Map<String, Object> sessionsMap = new HashMap<String, Object>(1);
Collection<Map<String, Object>> activeSessions = null;
String jsonRepresentation = null;
try {
activeSessions = this.singleSignOnSessionsReport.getActiveSsoSessions();
sessionsMap.put(ROOT_REPORT_ACTIVE_SESSIONS_KEY, activeSessions);
} | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
// Path: src/main/java/net/unicon/cas/addons/info/SingleSignOnSessionsReportResource.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
package net.unicon.cas.addons.info;
/**
* RESTful HTTP resource to expose <code>SingleSignOnSessionsReport</code> as <i>application/json</i> media type.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@Component
@Path("/")
public class SingleSignOnSessionsReportResource {
private final SingleSignOnSessionsReport singleSignOnSessionsReport;
private final ObjectMapper jsonMapper = new ObjectMapper();
private static final String ROOT_REPORT_ACTIVE_SESSIONS_KEY = "activeSsoSessions";
private static final String ROOT_REPORT_NA_KEY = "notAvailable";
private static final Logger logger = LoggerFactory.getLogger(SingleSignOnSessionsReportResource.class);
@Autowired
public SingleSignOnSessionsReportResource(SingleSignOnSessionsReport singleSignOnSessionsReport) {
this.singleSignOnSessionsReport = singleSignOnSessionsReport;
//Configure mapper strategies
this.jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
this.jsonMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response showActiveSsoSessions() {
Map<String, Object> sessionsMap = new HashMap<String, Object>(1);
Collection<Map<String, Object>> activeSessions = null;
String jsonRepresentation = null;
try {
activeSessions = this.singleSignOnSessionsReport.getActiveSsoSessions();
sessionsMap.put(ROOT_REPORT_ACTIVE_SESSIONS_KEY, activeSessions);
} | catch (BulkRetrievalOfTicketsNotSupportedException e) { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/ticket/internal/DefaultTicketSupport.java | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
| import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List; | package net.unicon.cas.addons.ticket.internal;
/**
* Default implementation of <code>TicketSupport</code>
* <p/>
* Uses CAS' <code>TicketRegistry</code> to retrieve TGT and its associated objects by provided tgt String token
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
// Path: src/main/java/net/unicon/cas/addons/ticket/internal/DefaultTicketSupport.java
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
package net.unicon.cas.addons.ticket.internal;
/**
* Default implementation of <code>TicketSupport</code>
* <p/>
* Uses CAS' <code>TicketRegistry</code> to retrieve TGT and its associated objects by provided tgt String token
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component | public class DefaultTicketSupport implements TicketSupport { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/ticket/internal/DefaultTicketSupport.java | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
| import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List; | package net.unicon.cas.addons.ticket.internal;
/**
* Default implementation of <code>TicketSupport</code>
* <p/>
* Uses CAS' <code>TicketRegistry</code> to retrieve TGT and its associated objects by provided tgt String token
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component
public class DefaultTicketSupport implements TicketSupport {
private final TicketRegistry ticketRegistry;
@Autowired
public DefaultTicketSupport(TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
@Override
public boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId) {
final Ticket ticket = this.ticketRegistry.getTicket(ticketGrantingTicketId);
if (ticket != null && ticket instanceof TicketGrantingTicket) {
return TicketGrantingTicket.class.cast(ticket).isExpired();
}
return false;
}
@Override
public void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId) {
if (ticketGrantingTicketExistsAndExpired(ticketGrantingTicketId)) {
this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
}
}
@Override | // Path: src/main/java/net/unicon/cas/addons/ticket/BulkRetrievalOfTicketsNotSupportedException.java
// public class BulkRetrievalOfTicketsNotSupportedException extends UnsupportedOperationException {
//
// private static final long serialVersionUID = 306893856892085373L;
//
// public BulkRetrievalOfTicketsNotSupportedException(String s) {
// super(s);
// }
//
// public BulkRetrievalOfTicketsNotSupportedException(String s, Throwable throwable) {
// super(s, throwable);
// }
// }
//
// Path: src/main/java/net/unicon/cas/addons/ticket/TicketSupport.java
// public interface TicketSupport {
//
// /**
// * Convenience method that deletes a provided TGT from the underlying ticket store
// * if that TGT is determined to be expired. If the provided ticket does not exist in a ticket store,
// * or not a <code>TicketGrantingTicket</code>, simply returns
// *
// * @param ticketGrantingTicketId for which to delete the underlying ticket
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId);
//
// /**
// * Convenience method to determine if a TicketGrantingTicket represented by a given id exists in a underlying ticket store
// * AND it is expired
// *
// * @param ticketGrantingTicketId representing TicketGrantingTicket
// * @return true if both predicate conditions satisfied, false otherwise
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions - runtime or otherwise
// */
// boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId);
//
// /**
// * Convenience method to return a collection of active (non-expired at the time of call) from CAS' underlying ticket store.
// *
// * @return a list of non-expired TGTs OR an empty list and NEVER <b>null</b>
// * <strong>NOTE TO IMPLEMENTERS:</strong> this method should never throw any exceptions other than
// * <code>BulkRetrievalOfTicketsNotSupportedException</code>
// * @throws BulkRetrievalOfTicketsNotSupportedException
// */
// List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException;
// }
// Path: src/main/java/net/unicon/cas/addons/ticket/internal/DefaultTicketSupport.java
import net.unicon.cas.addons.support.ThreadSafe;
import net.unicon.cas.addons.ticket.BulkRetrievalOfTicketsNotSupportedException;
import net.unicon.cas.addons.ticket.TicketSupport;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
package net.unicon.cas.addons.ticket.internal;
/**
* Default implementation of <code>TicketSupport</code>
* <p/>
* Uses CAS' <code>TicketRegistry</code> to retrieve TGT and its associated objects by provided tgt String token
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.3
*/
@ThreadSafe
@Component
public class DefaultTicketSupport implements TicketSupport {
private final TicketRegistry ticketRegistry;
@Autowired
public DefaultTicketSupport(TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
@Override
public boolean ticketGrantingTicketExistsAndExpired(String ticketGrantingTicketId) {
final Ticket ticket = this.ticketRegistry.getTicket(ticketGrantingTicketId);
if (ticket != null && ticket instanceof TicketGrantingTicket) {
return TicketGrantingTicket.class.cast(ticket).isExpired();
}
return false;
}
@Override
public void deleteExpiredTicketGrantingTicket(String ticketGrantingTicketId) {
if (ticketGrantingTicketExistsAndExpired(ticketGrantingTicketId)) {
this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
}
}
@Override | public List<TicketGrantingTicket> getNonExpiredTicketGrantingTickets() throws BulkRetrievalOfTicketsNotSupportedException { |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/web/flow/ServiceAuthorizationCheckWithCustomView.java | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
| import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.jasig.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import javax.validation.constraints.NotNull; | package net.unicon.cas.addons.web.flow;
/**
* Performs a basic check if an authentication request for a provided service is authorized to proceed
* based on the registered services registry configuration (or lack thereof).
* <p/>
* Adds an additional support for a custom <i>unauthorizedUrl</i> attribute in case of a registered service is
* not enabled.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.2
*/
public final class ServiceAuthorizationCheckWithCustomView extends AbstractAction {
@NotNull
private final ServicesManager servicesManager;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String DISABLED_SERVICE_URL_ATTRIBUTE = "disabledServiceUrl";
public ServiceAuthorizationCheckWithCustomView(final ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
@Override
protected Event doExecute(final RequestContext context) throws Exception {
final Service service = WebUtils.getService(context);
//No service == plain /login request. Return success indicating transition to the login form
if (service == null) {
return success();
}
final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
if (registeredService == null) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not defined in the service registry.", service.getId());
throw new UnauthorizedServiceException();
}
else if (!registeredService.isEnabled()) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not enabled in the service registry.", service.getId()); | // Path: src/main/java/net/unicon/cas/addons/serviceregistry/RegisteredServiceWithAttributes.java
// public interface RegisteredServiceWithAttributes extends RegisteredService {
//
// Map<String, Object> getExtraAttributes();
//
// }
// Path: src/main/java/net/unicon/cas/addons/web/flow/ServiceAuthorizationCheckWithCustomView.java
import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.jasig.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import javax.validation.constraints.NotNull;
package net.unicon.cas.addons.web.flow;
/**
* Performs a basic check if an authentication request for a provided service is authorized to proceed
* based on the registered services registry configuration (or lack thereof).
* <p/>
* Adds an additional support for a custom <i>unauthorizedUrl</i> attribute in case of a registered service is
* not enabled.
*
* @author Dmitriy Kopylenko
* @author Unicon, inc.
* @since 1.0.2
*/
public final class ServiceAuthorizationCheckWithCustomView extends AbstractAction {
@NotNull
private final ServicesManager servicesManager;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String DISABLED_SERVICE_URL_ATTRIBUTE = "disabledServiceUrl";
public ServiceAuthorizationCheckWithCustomView(final ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
@Override
protected Event doExecute(final RequestContext context) throws Exception {
final Service service = WebUtils.getService(context);
//No service == plain /login request. Return success indicating transition to the login form
if (service == null) {
return success();
}
final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
if (registeredService == null) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not defined in the service registry.", service.getId());
throw new UnauthorizedServiceException();
}
else if (!registeredService.isEnabled()) {
logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not enabled in the service registry.", service.getId()); | if (registeredService instanceof RegisteredServiceWithAttributes) { |
NaikSoftware/J2meLoader | app/src/main/java/javax/microedition/util/ContextHolder.java | // Path: app/src/main/java/ua/naiksoftware/j2meloader/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private String startPath;
// private static final String EXTS = ".jar.zip.java";
// private AppsListFragment appsListFragment;
// private final List<AppItem> apps = new ArrayList<AppItem>();
//
// /** Путь к папке со сконвертированными приложениями */
// private String pathConverted;
//
// private JarConverter converter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// startPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//
// pathConverted = getApplicationInfo().dataDir + "/converted/";
// appsListFragment = new AppsListFragment(apps);
// // update the main content by replacing fragments
// FragmentManager fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.container, appsListFragment).commit();
// updateApps();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// public void updateApps() {
// apps.clear();
// AppItem item;
// String author = getString(R.string.author);
// String version = getString(R.string.version);
// String[] appFolders = new File(pathConverted).list();
// if (!(appFolders == null)) {
// for (String appFolder : appFolders) {
// TreeMap<String, String> params = FileUtils
// .loadManifest(new File(pathConverted + appFolder
// + ConfScreen.MIDLET_CONF_FILE));
// item = new AppItem(R.drawable.app_default_icon,
// params.get("MIDlet-Name"), author
// + params.get("MIDlet-Vendor"), version
// + params.get("MIDlet-Version"));
// item.setPath(pathConverted + appFolder);
// apps.add(item);
// }
// }
// AppsListAdapter adapter = new AppsListAdapter(this, apps);
// appsListFragment.setListAdapter(adapter);
// }
// }
//
// Path: app/src/main/java/filelog/Log.java
// public class Log {
//
// private static final String token = " : ";
// private static final long MAX_LEN = 300 * 1024;//50 Kb
//
// public static void d(String tag, String message) {
// try {
// boolean noClear;
// File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt");
// if (file.length() > MAX_LEN) {
// noClear = false;
// } else {
// noClear = true;
// }
// FileWriter fw = new FileWriter(file, noClear);
// String msg = "\n" + new Date().toLocaleString() + token + tag + token + message;
// fw.write(msg);
// fw.flush();
// fw.close();
// //Log.d("L", msg);
// } catch (IOException e) {
// android.util.Log.e("L", "err in logging", e);
// }
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import ua.naiksoftware.j2meloader.MainActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.view.LayoutInflater;
import filelog.Log;
| /*
* Copyright 2012 Kulikov Dmitriy, Naik
*
* 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 javax.microedition.util;
public class ContextHolder {
private static final String tag = "ContextHolder";
| // Path: app/src/main/java/ua/naiksoftware/j2meloader/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private String startPath;
// private static final String EXTS = ".jar.zip.java";
// private AppsListFragment appsListFragment;
// private final List<AppItem> apps = new ArrayList<AppItem>();
//
// /** Путь к папке со сконвертированными приложениями */
// private String pathConverted;
//
// private JarConverter converter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// startPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//
// pathConverted = getApplicationInfo().dataDir + "/converted/";
// appsListFragment = new AppsListFragment(apps);
// // update the main content by replacing fragments
// FragmentManager fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.container, appsListFragment).commit();
// updateApps();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// public void updateApps() {
// apps.clear();
// AppItem item;
// String author = getString(R.string.author);
// String version = getString(R.string.version);
// String[] appFolders = new File(pathConverted).list();
// if (!(appFolders == null)) {
// for (String appFolder : appFolders) {
// TreeMap<String, String> params = FileUtils
// .loadManifest(new File(pathConverted + appFolder
// + ConfScreen.MIDLET_CONF_FILE));
// item = new AppItem(R.drawable.app_default_icon,
// params.get("MIDlet-Name"), author
// + params.get("MIDlet-Vendor"), version
// + params.get("MIDlet-Version"));
// item.setPath(pathConverted + appFolder);
// apps.add(item);
// }
// }
// AppsListAdapter adapter = new AppsListAdapter(this, apps);
// appsListFragment.setListAdapter(adapter);
// }
// }
//
// Path: app/src/main/java/filelog/Log.java
// public class Log {
//
// private static final String token = " : ";
// private static final long MAX_LEN = 300 * 1024;//50 Kb
//
// public static void d(String tag, String message) {
// try {
// boolean noClear;
// File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt");
// if (file.length() > MAX_LEN) {
// noClear = false;
// } else {
// noClear = true;
// }
// FileWriter fw = new FileWriter(file, noClear);
// String msg = "\n" + new Date().toLocaleString() + token + tag + token + message;
// fw.write(msg);
// fw.flush();
// fw.close();
// //Log.d("L", msg);
// } catch (IOException e) {
// android.util.Log.e("L", "err in logging", e);
// }
// }
// }
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import ua.naiksoftware.j2meloader.MainActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.view.LayoutInflater;
import filelog.Log;
/*
* Copyright 2012 Kulikov Dmitriy, Naik
*
* 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 javax.microedition.util;
public class ContextHolder {
private static final String tag = "ContextHolder";
| private static MainActivity context;
|
NaikSoftware/J2meLoader | app/src/main/java/javax/microedition/util/ContextHolder.java | // Path: app/src/main/java/ua/naiksoftware/j2meloader/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private String startPath;
// private static final String EXTS = ".jar.zip.java";
// private AppsListFragment appsListFragment;
// private final List<AppItem> apps = new ArrayList<AppItem>();
//
// /** Путь к папке со сконвертированными приложениями */
// private String pathConverted;
//
// private JarConverter converter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// startPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//
// pathConverted = getApplicationInfo().dataDir + "/converted/";
// appsListFragment = new AppsListFragment(apps);
// // update the main content by replacing fragments
// FragmentManager fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.container, appsListFragment).commit();
// updateApps();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// public void updateApps() {
// apps.clear();
// AppItem item;
// String author = getString(R.string.author);
// String version = getString(R.string.version);
// String[] appFolders = new File(pathConverted).list();
// if (!(appFolders == null)) {
// for (String appFolder : appFolders) {
// TreeMap<String, String> params = FileUtils
// .loadManifest(new File(pathConverted + appFolder
// + ConfScreen.MIDLET_CONF_FILE));
// item = new AppItem(R.drawable.app_default_icon,
// params.get("MIDlet-Name"), author
// + params.get("MIDlet-Vendor"), version
// + params.get("MIDlet-Version"));
// item.setPath(pathConverted + appFolder);
// apps.add(item);
// }
// }
// AppsListAdapter adapter = new AppsListAdapter(this, apps);
// appsListFragment.setListAdapter(adapter);
// }
// }
//
// Path: app/src/main/java/filelog/Log.java
// public class Log {
//
// private static final String token = " : ";
// private static final long MAX_LEN = 300 * 1024;//50 Kb
//
// public static void d(String tag, String message) {
// try {
// boolean noClear;
// File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt");
// if (file.length() > MAX_LEN) {
// noClear = false;
// } else {
// noClear = true;
// }
// FileWriter fw = new FileWriter(file, noClear);
// String msg = "\n" + new Date().toLocaleString() + token + tag + token + message;
// fw.write(msg);
// fw.flush();
// fw.close();
// //Log.d("L", msg);
// } catch (IOException e) {
// android.util.Log.e("L", "err in logging", e);
// }
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import ua.naiksoftware.j2meloader.MainActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.view.LayoutInflater;
import filelog.Log;
| /*
* Copyright 2012 Kulikov Dmitriy, Naik
*
* 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 javax.microedition.util;
public class ContextHolder {
private static final String tag = "ContextHolder";
private static MainActivity context;
private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>();
private static LayoutInflater inflater;
public static void setContext(MainActivity cx) {
context = cx;
inflater = LayoutInflater.from(cx);
}
public static Context getContext() {
if (context == null) {
throw new IllegalStateException(
"call setContext() before calling getContext()");
}
return context;
}
public static LayoutInflater getInflater() {
return inflater;
}
public static InputStream getResourceAsStream(String filename) {
if (filename.startsWith("/")) {
filename = filename.substring(1);
}
try {
return getContext().getAssets().open(filename);
} catch (IOException e) {
| // Path: app/src/main/java/ua/naiksoftware/j2meloader/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private String startPath;
// private static final String EXTS = ".jar.zip.java";
// private AppsListFragment appsListFragment;
// private final List<AppItem> apps = new ArrayList<AppItem>();
//
// /** Путь к папке со сконвертированными приложениями */
// private String pathConverted;
//
// private JarConverter converter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// startPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//
// pathConverted = getApplicationInfo().dataDir + "/converted/";
// appsListFragment = new AppsListFragment(apps);
// // update the main content by replacing fragments
// FragmentManager fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.container, appsListFragment).commit();
// updateApps();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// public void updateApps() {
// apps.clear();
// AppItem item;
// String author = getString(R.string.author);
// String version = getString(R.string.version);
// String[] appFolders = new File(pathConverted).list();
// if (!(appFolders == null)) {
// for (String appFolder : appFolders) {
// TreeMap<String, String> params = FileUtils
// .loadManifest(new File(pathConverted + appFolder
// + ConfScreen.MIDLET_CONF_FILE));
// item = new AppItem(R.drawable.app_default_icon,
// params.get("MIDlet-Name"), author
// + params.get("MIDlet-Vendor"), version
// + params.get("MIDlet-Version"));
// item.setPath(pathConverted + appFolder);
// apps.add(item);
// }
// }
// AppsListAdapter adapter = new AppsListAdapter(this, apps);
// appsListFragment.setListAdapter(adapter);
// }
// }
//
// Path: app/src/main/java/filelog/Log.java
// public class Log {
//
// private static final String token = " : ";
// private static final long MAX_LEN = 300 * 1024;//50 Kb
//
// public static void d(String tag, String message) {
// try {
// boolean noClear;
// File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt");
// if (file.length() > MAX_LEN) {
// noClear = false;
// } else {
// noClear = true;
// }
// FileWriter fw = new FileWriter(file, noClear);
// String msg = "\n" + new Date().toLocaleString() + token + tag + token + message;
// fw.write(msg);
// fw.flush();
// fw.close();
// //Log.d("L", msg);
// } catch (IOException e) {
// android.util.Log.e("L", "err in logging", e);
// }
// }
// }
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import ua.naiksoftware.j2meloader.MainActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.view.LayoutInflater;
import filelog.Log;
/*
* Copyright 2012 Kulikov Dmitriy, Naik
*
* 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 javax.microedition.util;
public class ContextHolder {
private static final String tag = "ContextHolder";
private static MainActivity context;
private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>();
private static LayoutInflater inflater;
public static void setContext(MainActivity cx) {
context = cx;
inflater = LayoutInflater.from(cx);
}
public static Context getContext() {
if (context == null) {
throw new IllegalStateException(
"call setContext() before calling getContext()");
}
return context;
}
public static LayoutInflater getInflater() {
return inflater;
}
public static InputStream getResourceAsStream(String filename) {
if (filename.startsWith("/")) {
filename = filename.substring(1);
}
try {
return getContext().getAssets().open(filename);
} catch (IOException e) {
| Log.d(tag, "getResourceAsStream err: " + e.getMessage());
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.