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
schaloner/deadbolt
app/controllers/deadbolt/AbstractDeadboltHandler.java
// Path: app/models/deadbolt/NullRoleHolder.java // public class NullRoleHolder implements RoleHolder // { // public static final RoleHolder NULL_OBJECT = new NullRoleHolder(); // // /** // * {@inheritDoc} // */ // public List<Role> getRoles() // { // return Collections.emptyList(); // } // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import models.deadbolt.NullRoleHolder; import models.deadbolt.RoleHolder;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AbstractDeadboltHandler implements DeadboltHandler { /** * {@inheritDoc} */
// Path: app/models/deadbolt/NullRoleHolder.java // public class NullRoleHolder implements RoleHolder // { // public static final RoleHolder NULL_OBJECT = new NullRoleHolder(); // // /** // * {@inheritDoc} // */ // public List<Role> getRoles() // { // return Collections.emptyList(); // } // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/AbstractDeadboltHandler.java import models.deadbolt.NullRoleHolder; import models.deadbolt.RoleHolder; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AbstractDeadboltHandler implements DeadboltHandler { /** * {@inheritDoc} */
public RoleHolder getRoleHolder()
schaloner/deadbolt
app/controllers/deadbolt/AbstractDeadboltHandler.java
// Path: app/models/deadbolt/NullRoleHolder.java // public class NullRoleHolder implements RoleHolder // { // public static final RoleHolder NULL_OBJECT = new NullRoleHolder(); // // /** // * {@inheritDoc} // */ // public List<Role> getRoles() // { // return Collections.emptyList(); // } // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import models.deadbolt.NullRoleHolder; import models.deadbolt.RoleHolder;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AbstractDeadboltHandler implements DeadboltHandler { /** * {@inheritDoc} */ public RoleHolder getRoleHolder() {
// Path: app/models/deadbolt/NullRoleHolder.java // public class NullRoleHolder implements RoleHolder // { // public static final RoleHolder NULL_OBJECT = new NullRoleHolder(); // // /** // * {@inheritDoc} // */ // public List<Role> getRoles() // { // return Collections.emptyList(); // } // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/AbstractDeadboltHandler.java import models.deadbolt.NullRoleHolder; import models.deadbolt.RoleHolder; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AbstractDeadboltHandler implements DeadboltHandler { /** * {@inheritDoc} */ public RoleHolder getRoleHolder() {
return NullRoleHolder.NULL_OBJECT;
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AclRestrictedResourcesHandler.java
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: samples-and-tests/acl/app/security/AccessChainHandler.java // public abstract class AccessChainHandler implements RestrictedResourcesHandler // { // public AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters) // { // String currentUserName = AclController.getCurrentUserName(); // Http.Request request = Http.Request.current(); // String targetUserName = request.params.get("targetUserName"); // // AccessResult accessResult = AccessResult.DENIED; // if (targetUserName == null || currentUserName.equals(targetUserName)) // { // // current user is viewing own information // accessResult = AccessResult.ALLOWED; // } // else // { // AclUser targetUser = AclUser.getByUserName(targetUserName); // // switch (getAccessChain(targetUser.accessControlPreference)) // { // case FRIENDS: // AclUser currentUser = AclUser.getByUserName(currentUserName); // accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; // break; // case ANYONE: // accessResult = AccessResult.ALLOWED; // break; // } // } // // return accessResult; // } // // public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference); // }
import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import models.deadbolt.AccessResult; import security.AccessChainHandler; import java.util.HashMap; import java.util.List; import java.util.Map;
package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclRestrictedResourcesHandler implements RestrictedResourcesHandler { private static Map<String, RestrictedResourcesHandler> HANDLERS = new HashMap<String, RestrictedResourcesHandler>(); static { HANDLERS.put("friends",
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: samples-and-tests/acl/app/security/AccessChainHandler.java // public abstract class AccessChainHandler implements RestrictedResourcesHandler // { // public AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters) // { // String currentUserName = AclController.getCurrentUserName(); // Http.Request request = Http.Request.current(); // String targetUserName = request.params.get("targetUserName"); // // AccessResult accessResult = AccessResult.DENIED; // if (targetUserName == null || currentUserName.equals(targetUserName)) // { // // current user is viewing own information // accessResult = AccessResult.ALLOWED; // } // else // { // AclUser targetUser = AclUser.getByUserName(targetUserName); // // switch (getAccessChain(targetUser.accessControlPreference)) // { // case FRIENDS: // AclUser currentUser = AclUser.getByUserName(currentUserName); // accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; // break; // case ANYONE: // accessResult = AccessResult.ALLOWED; // break; // } // } // // return accessResult; // } // // public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference); // } // Path: samples-and-tests/acl/app/controllers/AclRestrictedResourcesHandler.java import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import models.deadbolt.AccessResult; import security.AccessChainHandler; import java.util.HashMap; import java.util.List; import java.util.Map; package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclRestrictedResourcesHandler implements RestrictedResourcesHandler { private static Map<String, RestrictedResourcesHandler> HANDLERS = new HashMap<String, RestrictedResourcesHandler>(); static { HANDLERS.put("friends",
new AccessChainHandler()
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AclRestrictedResourcesHandler.java
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: samples-and-tests/acl/app/security/AccessChainHandler.java // public abstract class AccessChainHandler implements RestrictedResourcesHandler // { // public AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters) // { // String currentUserName = AclController.getCurrentUserName(); // Http.Request request = Http.Request.current(); // String targetUserName = request.params.get("targetUserName"); // // AccessResult accessResult = AccessResult.DENIED; // if (targetUserName == null || currentUserName.equals(targetUserName)) // { // // current user is viewing own information // accessResult = AccessResult.ALLOWED; // } // else // { // AclUser targetUser = AclUser.getByUserName(targetUserName); // // switch (getAccessChain(targetUser.accessControlPreference)) // { // case FRIENDS: // AclUser currentUser = AclUser.getByUserName(currentUserName); // accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; // break; // case ANYONE: // accessResult = AccessResult.ALLOWED; // break; // } // } // // return accessResult; // } // // public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference); // }
import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import models.deadbolt.AccessResult; import security.AccessChainHandler; import java.util.HashMap; import java.util.List; import java.util.Map;
package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclRestrictedResourcesHandler implements RestrictedResourcesHandler { private static Map<String, RestrictedResourcesHandler> HANDLERS = new HashMap<String, RestrictedResourcesHandler>(); static { HANDLERS.put("friends", new AccessChainHandler() {
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: samples-and-tests/acl/app/security/AccessChainHandler.java // public abstract class AccessChainHandler implements RestrictedResourcesHandler // { // public AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters) // { // String currentUserName = AclController.getCurrentUserName(); // Http.Request request = Http.Request.current(); // String targetUserName = request.params.get("targetUserName"); // // AccessResult accessResult = AccessResult.DENIED; // if (targetUserName == null || currentUserName.equals(targetUserName)) // { // // current user is viewing own information // accessResult = AccessResult.ALLOWED; // } // else // { // AclUser targetUser = AclUser.getByUserName(targetUserName); // // switch (getAccessChain(targetUser.accessControlPreference)) // { // case FRIENDS: // AclUser currentUser = AclUser.getByUserName(currentUserName); // accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; // break; // case ANYONE: // accessResult = AccessResult.ALLOWED; // break; // } // } // // return accessResult; // } // // public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference); // } // Path: samples-and-tests/acl/app/controllers/AclRestrictedResourcesHandler.java import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import models.deadbolt.AccessResult; import security.AccessChainHandler; import java.util.HashMap; import java.util.List; import java.util.Map; package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclRestrictedResourcesHandler implements RestrictedResourcesHandler { private static Map<String, RestrictedResourcesHandler> HANDLERS = new HashMap<String, RestrictedResourcesHandler>(); static { HANDLERS.put("friends", new AccessChainHandler() {
public AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference)
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AclRestrictedResourcesHandler.java
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: samples-and-tests/acl/app/security/AccessChainHandler.java // public abstract class AccessChainHandler implements RestrictedResourcesHandler // { // public AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters) // { // String currentUserName = AclController.getCurrentUserName(); // Http.Request request = Http.Request.current(); // String targetUserName = request.params.get("targetUserName"); // // AccessResult accessResult = AccessResult.DENIED; // if (targetUserName == null || currentUserName.equals(targetUserName)) // { // // current user is viewing own information // accessResult = AccessResult.ALLOWED; // } // else // { // AclUser targetUser = AclUser.getByUserName(targetUserName); // // switch (getAccessChain(targetUser.accessControlPreference)) // { // case FRIENDS: // AclUser currentUser = AclUser.getByUserName(currentUserName); // accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; // break; // case ANYONE: // accessResult = AccessResult.ALLOWED; // break; // } // } // // return accessResult; // } // // public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference); // }
import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import models.deadbolt.AccessResult; import security.AccessChainHandler; import java.util.HashMap; import java.util.List; import java.util.Map;
package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclRestrictedResourcesHandler implements RestrictedResourcesHandler { private static Map<String, RestrictedResourcesHandler> HANDLERS = new HashMap<String, RestrictedResourcesHandler>(); static { HANDLERS.put("friends", new AccessChainHandler() { public AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference) { return preference.friendVisibility; } }); HANDLERS.put("photos", new AccessChainHandler() { public AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference) { return preference.photoVisibility; } }); // we can always see status updates, regardless of the user's preference HANDLERS.put("statusUpdates", new RestrictedResourcesHandler() {
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: samples-and-tests/acl/app/security/AccessChainHandler.java // public abstract class AccessChainHandler implements RestrictedResourcesHandler // { // public AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters) // { // String currentUserName = AclController.getCurrentUserName(); // Http.Request request = Http.Request.current(); // String targetUserName = request.params.get("targetUserName"); // // AccessResult accessResult = AccessResult.DENIED; // if (targetUserName == null || currentUserName.equals(targetUserName)) // { // // current user is viewing own information // accessResult = AccessResult.ALLOWED; // } // else // { // AclUser targetUser = AclUser.getByUserName(targetUserName); // // switch (getAccessChain(targetUser.accessControlPreference)) // { // case FRIENDS: // AclUser currentUser = AclUser.getByUserName(currentUserName); // accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; // break; // case ANYONE: // accessResult = AccessResult.ALLOWED; // break; // } // } // // return accessResult; // } // // public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference); // } // Path: samples-and-tests/acl/app/controllers/AclRestrictedResourcesHandler.java import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import models.deadbolt.AccessResult; import security.AccessChainHandler; import java.util.HashMap; import java.util.List; import java.util.Map; package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclRestrictedResourcesHandler implements RestrictedResourcesHandler { private static Map<String, RestrictedResourcesHandler> HANDLERS = new HashMap<String, RestrictedResourcesHandler>(); static { HANDLERS.put("friends", new AccessChainHandler() { public AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference) { return preference.friendVisibility; } }); HANDLERS.put("photos", new AccessChainHandler() { public AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference) { return preference.photoVisibility; } }); // we can always see status updates, regardless of the user's preference HANDLERS.put("statusUpdates", new RestrictedResourcesHandler() {
public AccessResult checkAccess(List<String> resourceNames,
schaloner/deadbolt
samples-and-tests/acl/app/security/AccessChainHandler.java
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // }
import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map;
package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler {
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // Path: samples-and-tests/acl/app/security/AccessChainHandler.java import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map; package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler {
public AccessResult checkAccess(List<String> resourceNames,
schaloner/deadbolt
samples-and-tests/acl/app/security/AccessChainHandler.java
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // }
import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map;
package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler { public AccessResult checkAccess(List<String> resourceNames, Map<String, String> resourceParameters) {
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // Path: samples-and-tests/acl/app/security/AccessChainHandler.java import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map; package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler { public AccessResult checkAccess(List<String> resourceNames, Map<String, String> resourceParameters) {
String currentUserName = AclController.getCurrentUserName();
schaloner/deadbolt
samples-and-tests/acl/app/security/AccessChainHandler.java
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // }
import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map;
package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler { public AccessResult checkAccess(List<String> resourceNames, Map<String, String> resourceParameters) { String currentUserName = AclController.getCurrentUserName(); Http.Request request = Http.Request.current(); String targetUserName = request.params.get("targetUserName"); AccessResult accessResult = AccessResult.DENIED; if (targetUserName == null || currentUserName.equals(targetUserName)) { // current user is viewing own information accessResult = AccessResult.ALLOWED; } else {
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // Path: samples-and-tests/acl/app/security/AccessChainHandler.java import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map; package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler { public AccessResult checkAccess(List<String> resourceNames, Map<String, String> resourceParameters) { String currentUserName = AclController.getCurrentUserName(); Http.Request request = Http.Request.current(); String targetUserName = request.params.get("targetUserName"); AccessResult accessResult = AccessResult.DENIED; if (targetUserName == null || currentUserName.equals(targetUserName)) { // current user is viewing own information accessResult = AccessResult.ALLOWED; } else {
AclUser targetUser = AclUser.getByUserName(targetUserName);
schaloner/deadbolt
samples-and-tests/acl/app/security/AccessChainHandler.java
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // }
import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map;
package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler { public AccessResult checkAccess(List<String> resourceNames, Map<String, String> resourceParameters) { String currentUserName = AclController.getCurrentUserName(); Http.Request request = Http.Request.current(); String targetUserName = request.params.get("targetUserName"); AccessResult accessResult = AccessResult.DENIED; if (targetUserName == null || currentUserName.equals(targetUserName)) { // current user is viewing own information accessResult = AccessResult.ALLOWED; } else { AclUser targetUser = AclUser.getByUserName(targetUserName); switch (getAccessChain(targetUser.accessControlPreference)) { case FRIENDS: AclUser currentUser = AclUser.getByUserName(currentUserName); accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; break; case ANYONE: accessResult = AccessResult.ALLOWED; break; } } return accessResult; }
// Path: samples-and-tests/acl/app/controllers/AclController.java // @With(Deadbolt.class) // public class AclController extends Controller // { // @Util // public static String getCurrentUserName() // { // return Secure.Security.connected(); // } // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // Path: samples-and-tests/acl/app/security/AccessChainHandler.java import controllers.AclController; import controllers.deadbolt.RestrictedResourcesHandler; import model.AccessControlPreference; import model.AclUser; import models.deadbolt.AccessResult; import play.mvc.Http; import java.security.AccessController; import java.util.List; import java.util.Map; package security; /** * @author Steve Chaloner (steve@objectify.be) */ public abstract class AccessChainHandler implements RestrictedResourcesHandler { public AccessResult checkAccess(List<String> resourceNames, Map<String, String> resourceParameters) { String currentUserName = AclController.getCurrentUserName(); Http.Request request = Http.Request.current(); String targetUserName = request.params.get("targetUserName"); AccessResult accessResult = AccessResult.DENIED; if (targetUserName == null || currentUserName.equals(targetUserName)) { // current user is viewing own information accessResult = AccessResult.ALLOWED; } else { AclUser targetUser = AclUser.getByUserName(targetUserName); switch (getAccessChain(targetUser.accessControlPreference)) { case FRIENDS: AclUser currentUser = AclUser.getByUserName(currentUserName); accessResult = targetUser.isFriend(currentUser) ? AccessResult.ALLOWED : AccessResult.DENIED; break; case ANYONE: accessResult = AccessResult.ALLOWED; break; } } return accessResult; }
public abstract AccessControlPreference.AccessChain getAccessChain(AccessControlPreference preference);
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AclDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import model.AclUser; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclDeadboltHandler extends Controller implements DeadboltHandler {
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/acl/app/controllers/AclDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import model.AclUser; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclDeadboltHandler extends Controller implements DeadboltHandler {
private static final RestrictedResourcesHandler RESTRICTED_RESOURCES_HANDLER = new AclRestrictedResourcesHandler();
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AclDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import model.AclUser; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return AclUser.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); } public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() { return new ExternalizedRestrictionsAccessor() {
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/acl/app/controllers/AclDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import model.AclUser; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return AclUser.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); } public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() { return new ExternalizedRestrictionsAccessor() {
public ExternalizedRestrictions getExternalizedRestrictions(String name)
schaloner/deadbolt
samples-and-tests/restriction-samples/app/controllers/MyRestrictedResourcesHandler.java
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // }
import controllers.deadbolt.RestrictedResourcesHandler; import models.deadbolt.AccessResult; import java.util.List; import java.util.Map;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyRestrictedResourcesHandler implements RestrictedResourcesHandler { /** * Various things can be done here, such as checking in a database table that maps the resource name to the * current user name or a group the user is in. There are two rules and one guideline for an easy life here: * <ol> * <li>If access is allowed, return {@link AccessResult#ALLOWED}</li> * <li>If access is denied, return {@link AccessResult#DENIED}</li> * <li>If access is not specified in, e.g. the database you can choose to return {@link AccessResult#ALLOWED} * or {@link AccessResult#DENIED} if you have a hard policy for this situation; alternatively you can return * {@link AccessResult#NOT_SPECIFIED} and allow further processing.</li> * </ol> * * {@inheritDoc} */
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // Path: samples-and-tests/restriction-samples/app/controllers/MyRestrictedResourcesHandler.java import controllers.deadbolt.RestrictedResourcesHandler; import models.deadbolt.AccessResult; import java.util.List; import java.util.Map; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyRestrictedResourcesHandler implements RestrictedResourcesHandler { /** * Various things can be done here, such as checking in a database table that maps the resource name to the * current user name or a group the user is in. There are two rules and one guideline for an easy life here: * <ol> * <li>If access is allowed, return {@link AccessResult#ALLOWED}</li> * <li>If access is denied, return {@link AccessResult#DENIED}</li> * <li>If access is not specified in, e.g. the database you can choose to return {@link AccessResult#ALLOWED} * or {@link AccessResult#DENIED} if you have a hard policy for this situation; alternatively you can return * {@link AccessResult#NOT_SPECIFIED} and allow further processing.</li> * </ol> * * {@inheritDoc} */
public AccessResult checkAccess(List<String> resourceNames,
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyDeadboltHandler extends Controller implements DeadboltHandler { public void beforeRoleCheck() { // Note that if you provide your own implementation of Secure's Security class you would refer to that instead if (!Secure.Security.isConnected()) { try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } }
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyDeadboltHandler extends Controller implements DeadboltHandler { public void beforeRoleCheck() { // Note that if you provide your own implementation of Secure's Security class you would refer to that instead if (!Secure.Security.isConnected()) { try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } }
public RoleHolder getRoleHolder()
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyDeadboltHandler extends Controller implements DeadboltHandler { public void beforeRoleCheck() { // Note that if you provide your own implementation of Secure's Security class you would refer to that instead if (!Secure.Security.isConnected()) { try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected();
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyDeadboltHandler extends Controller implements DeadboltHandler { public void beforeRoleCheck() { // Note that if you provide your own implementation of Secure's Security class you would refer to that instead if (!Secure.Security.isConnected()) { try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected();
return User.getByUserName(userName);
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyDeadboltHandler extends Controller implements DeadboltHandler { public void beforeRoleCheck() { // Note that if you provide your own implementation of Secure's Security class you would refer to that instead if (!Secure.Security.isConnected()) { try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return User.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); }
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyDeadboltHandler extends Controller implements DeadboltHandler { public void beforeRoleCheck() { // Note that if you provide your own implementation of Secure's Security class you would refer to that instead if (!Secure.Security.isConnected()) { try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return User.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); }
public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor()
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return User.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); } public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() { return new ExternalizedRestrictionsAccessor() {
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; try { if (!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : "/"); Secure.login(); } } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return User.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); } public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() { return new ExternalizedRestrictionsAccessor() {
public ExternalizedRestrictions getExternalizedRestrictions(String name)
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
} catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return User.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); } public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() { return new ExternalizedRestrictionsAccessor() { public ExternalizedRestrictions getExternalizedRestrictions(String name) { return null; } }; }
// Path: app/controllers/deadbolt/DeadboltHandler.java // public interface DeadboltHandler // { // /** // * Invoked immediately before controller or view restrictions are checked. This forms the integration with any // * authentication actions that may need to occur. // */ // void beforeRoleCheck(); // // /** // * Gets the current {@link RoleHolder}, e.g. the current user. // * // * @return the current role holder // */ // RoleHolder getRoleHolder(); // // /** // * Invoked when an access failure is detected on <i>controllerClassName</i>. // * // * @param controllerClassName the name of the controller access was denied to // */ // void onAccessFailure(String controllerClassName); // // /** // * Gets the accessor used to determine restrictions from an external source. // * // * @return the accessor for externalised restrictions. May be null. // */ // ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor(); // // /** // * Gets the handler used for dealing with resources restricted to specific users/groups. // * // * @return the handler for restricted resources. May be null. // */ // RestrictedResourcesHandler getRestrictedResourcesHandler(); // } // // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/integration-with-secure/app/controllers/MyDeadboltHandler.java import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import models.User; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller; } catch (Throwable t) { // handle this in an app-specific way } } } public RoleHolder getRoleHolder() { String userName = Secure.Security.connected(); return User.getByUserName(userName); } public void onAccessFailure(String controllerClassName) { forbidden(); } public ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor() { return new ExternalizedRestrictionsAccessor() { public ExternalizedRestrictions getExternalizedRestrictions(String name) { return null; } }; }
public RestrictedResourcesHandler getRestrictedResourcesHandler()
schaloner/deadbolt
samples-and-tests/unrestricted-samples/app/controllers/MyRestrictedResourcesHandler.java
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // }
import controllers.deadbolt.RestrictedResourcesHandler; import models.deadbolt.AccessResult; import java.util.List; import java.util.Map;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyRestrictedResourcesHandler implements RestrictedResourcesHandler { /** * Various things can be done here, such as checking in a database table that maps the resource name to the * current user name or a group the user is in. There are two rules and one guideline for an easy life here: * <ol> * <li>If access is allowed, return {@link models.deadbolt.AccessResult#ALLOWED}</li> * <li>If access is denied, return {@link models.deadbolt.AccessResult#DENIED}</li> * <li>If access is not specified in, e.g. the database you can choose to return {@link models.deadbolt.AccessResult#ALLOWED} * or {@link models.deadbolt.AccessResult#DENIED} if you have a hard policy for this situation; alternatively you can return * {@link models.deadbolt.AccessResult#NOT_SPECIFIED} and allow further processing.</li> * </ol> * * {@inheritDoc} */
// Path: app/controllers/deadbolt/RestrictedResourcesHandler.java // public interface RestrictedResourcesHandler // { // /** // * Check the access of someone, typically the current user, for the named resource. // * // * <ul> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li> // * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and // * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or // * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present, // * access will be allowed.</li> // * </ul> // * // * @param resourceNames the names of the resource // * @param resourceParameters additional information on the resource // * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied. // * {@link AccessResult#NOT_SPECIFIED} if access is not specified. // */ // AccessResult checkAccess(List<String> resourceNames, // Map<String, String> resourceParameters); // } // // Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // Path: samples-and-tests/unrestricted-samples/app/controllers/MyRestrictedResourcesHandler.java import controllers.deadbolt.RestrictedResourcesHandler; import models.deadbolt.AccessResult; import java.util.List; import java.util.Map; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyRestrictedResourcesHandler implements RestrictedResourcesHandler { /** * Various things can be done here, such as checking in a database table that maps the resource name to the * current user name or a group the user is in. There are two rules and one guideline for an easy life here: * <ol> * <li>If access is allowed, return {@link models.deadbolt.AccessResult#ALLOWED}</li> * <li>If access is denied, return {@link models.deadbolt.AccessResult#DENIED}</li> * <li>If access is not specified in, e.g. the database you can choose to return {@link models.deadbolt.AccessResult#ALLOWED} * or {@link models.deadbolt.AccessResult#DENIED} if you have a hard policy for this situation; alternatively you can return * {@link models.deadbolt.AccessResult#NOT_SPECIFIED} and allow further processing.</li> * </ol> * * {@inheritDoc} */
public AccessResult checkAccess(List<String> resourceNames,
schaloner/deadbolt
samples-and-tests/unrestricted-samples/app/models/MyRoleHolder.java
// Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import models.deadbolt.Role; import models.deadbolt.RoleHolder; import java.util.Arrays; import java.util.List;
/* * Copyright 2010-2011 Steve Chaloner * * 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 models; /** * @author Steve Chaloner (steve@objectify.be). */ public class MyRoleHolder implements RoleHolder {
// Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/unrestricted-samples/app/models/MyRoleHolder.java import models.deadbolt.Role; import models.deadbolt.RoleHolder; import java.util.Arrays; import java.util.List; /* * Copyright 2010-2011 Steve Chaloner * * 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 models; /** * @author Steve Chaloner (steve@objectify.be). */ public class MyRoleHolder implements RoleHolder {
public List<? extends Role> getRoles()
schaloner/deadbolt
app/controllers/deadbolt/DeadboltHandler.java
// Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import models.deadbolt.RoleHolder;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be) */ public interface DeadboltHandler { /** * Invoked immediately before controller or view restrictions are checked. This forms the integration with any * authentication actions that may need to occur. */ void beforeRoleCheck(); /** * Gets the current {@link RoleHolder}, e.g. the current user. * * @return the current role holder */
// Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/DeadboltHandler.java import models.deadbolt.RoleHolder; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be) */ public interface DeadboltHandler { /** * Invoked immediately before controller or view restrictions are checked. This forms the integration with any * authentication actions that may need to occur. */ void beforeRoleCheck(); /** * Gets the current {@link RoleHolder}, e.g. the current user. * * @return the current role holder */
RoleHolder getRoleHolder();
schaloner/deadbolt
app/controllers/deadbolt/reports/DeadboltReporter.java
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // // Path: app/models/deadbolt/reports/MethodReport.java // public class MethodReport // { // public final String name; // // public final List<String> dynamicChecks = new ArrayList<String>(); // // public final List<String> staticChecks = new ArrayList<String>(); // // public MethodReport(String name) // { // this.name = name; // } // // public void addStaticCheck(String staticCheck) // { // staticChecks.add(staticCheck); // } // // public void addDynamicCheck(String dynamicCheck) // { // staticChecks.add(dynamicCheck); // } // // } // // Path: app/models/deadbolt/reports/ProjectReport.java // public class ProjectReport // { // public String projectName; // // public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>(); // // public void addControllerReport(ControllerReport controllerReport) // { // controllerReports.add(controllerReport); // } // }
import controllers.deadbolt.RestrictedResource; import models.deadbolt.reports.ControllerReport; import models.deadbolt.reports.MethodReport; import models.deadbolt.reports.ProjectReport; import play.Play; import play.mvc.Before; import play.mvc.Controller; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List;
package controllers.deadbolt.reports; /** * Provides a report on the restrictions imposed with Deadbolt. * * @author Steve Chaloner (steve@objectify.be) */ public class DeadboltReporter extends Controller { @Before public static void disableInProduction() { if (Play.mode == Play.Mode.PROD) { error(404, "Page not found"); } } public static void report() {
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // // Path: app/models/deadbolt/reports/MethodReport.java // public class MethodReport // { // public final String name; // // public final List<String> dynamicChecks = new ArrayList<String>(); // // public final List<String> staticChecks = new ArrayList<String>(); // // public MethodReport(String name) // { // this.name = name; // } // // public void addStaticCheck(String staticCheck) // { // staticChecks.add(staticCheck); // } // // public void addDynamicCheck(String dynamicCheck) // { // staticChecks.add(dynamicCheck); // } // // } // // Path: app/models/deadbolt/reports/ProjectReport.java // public class ProjectReport // { // public String projectName; // // public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>(); // // public void addControllerReport(ControllerReport controllerReport) // { // controllerReports.add(controllerReport); // } // } // Path: app/controllers/deadbolt/reports/DeadboltReporter.java import controllers.deadbolt.RestrictedResource; import models.deadbolt.reports.ControllerReport; import models.deadbolt.reports.MethodReport; import models.deadbolt.reports.ProjectReport; import play.Play; import play.mvc.Before; import play.mvc.Controller; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; package controllers.deadbolt.reports; /** * Provides a report on the restrictions imposed with Deadbolt. * * @author Steve Chaloner (steve@objectify.be) */ public class DeadboltReporter extends Controller { @Before public static void disableInProduction() { if (Play.mode == Play.Mode.PROD) { error(404, "Page not found"); } } public static void report() {
ProjectReport projectReport = new ProjectReport();
schaloner/deadbolt
app/controllers/deadbolt/reports/DeadboltReporter.java
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // // Path: app/models/deadbolt/reports/MethodReport.java // public class MethodReport // { // public final String name; // // public final List<String> dynamicChecks = new ArrayList<String>(); // // public final List<String> staticChecks = new ArrayList<String>(); // // public MethodReport(String name) // { // this.name = name; // } // // public void addStaticCheck(String staticCheck) // { // staticChecks.add(staticCheck); // } // // public void addDynamicCheck(String dynamicCheck) // { // staticChecks.add(dynamicCheck); // } // // } // // Path: app/models/deadbolt/reports/ProjectReport.java // public class ProjectReport // { // public String projectName; // // public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>(); // // public void addControllerReport(ControllerReport controllerReport) // { // controllerReports.add(controllerReport); // } // }
import controllers.deadbolt.RestrictedResource; import models.deadbolt.reports.ControllerReport; import models.deadbolt.reports.MethodReport; import models.deadbolt.reports.ProjectReport; import play.Play; import play.mvc.Before; import play.mvc.Controller; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List;
package controllers.deadbolt.reports; /** * Provides a report on the restrictions imposed with Deadbolt. * * @author Steve Chaloner (steve@objectify.be) */ public class DeadboltReporter extends Controller { @Before public static void disableInProduction() { if (Play.mode == Play.Mode.PROD) { error(404, "Page not found"); } } public static void report() { ProjectReport projectReport = new ProjectReport(); projectReport.projectName = Play.configuration.getProperty("application.name"); List<Class> controllers = Play.classloader.getAssignableClasses(Controller.class); for (Class controller : controllers) {
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // // Path: app/models/deadbolt/reports/MethodReport.java // public class MethodReport // { // public final String name; // // public final List<String> dynamicChecks = new ArrayList<String>(); // // public final List<String> staticChecks = new ArrayList<String>(); // // public MethodReport(String name) // { // this.name = name; // } // // public void addStaticCheck(String staticCheck) // { // staticChecks.add(staticCheck); // } // // public void addDynamicCheck(String dynamicCheck) // { // staticChecks.add(dynamicCheck); // } // // } // // Path: app/models/deadbolt/reports/ProjectReport.java // public class ProjectReport // { // public String projectName; // // public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>(); // // public void addControllerReport(ControllerReport controllerReport) // { // controllerReports.add(controllerReport); // } // } // Path: app/controllers/deadbolt/reports/DeadboltReporter.java import controllers.deadbolt.RestrictedResource; import models.deadbolt.reports.ControllerReport; import models.deadbolt.reports.MethodReport; import models.deadbolt.reports.ProjectReport; import play.Play; import play.mvc.Before; import play.mvc.Controller; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; package controllers.deadbolt.reports; /** * Provides a report on the restrictions imposed with Deadbolt. * * @author Steve Chaloner (steve@objectify.be) */ public class DeadboltReporter extends Controller { @Before public static void disableInProduction() { if (Play.mode == Play.Mode.PROD) { error(404, "Page not found"); } } public static void report() { ProjectReport projectReport = new ProjectReport(); projectReport.projectName = Play.configuration.getProperty("application.name"); List<Class> controllers = Play.classloader.getAssignableClasses(Controller.class); for (Class controller : controllers) {
ControllerReport controllerReport = getControllerReport(controller);
schaloner/deadbolt
app/controllers/deadbolt/reports/DeadboltReporter.java
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // // Path: app/models/deadbolt/reports/MethodReport.java // public class MethodReport // { // public final String name; // // public final List<String> dynamicChecks = new ArrayList<String>(); // // public final List<String> staticChecks = new ArrayList<String>(); // // public MethodReport(String name) // { // this.name = name; // } // // public void addStaticCheck(String staticCheck) // { // staticChecks.add(staticCheck); // } // // public void addDynamicCheck(String dynamicCheck) // { // staticChecks.add(dynamicCheck); // } // // } // // Path: app/models/deadbolt/reports/ProjectReport.java // public class ProjectReport // { // public String projectName; // // public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>(); // // public void addControllerReport(ControllerReport controllerReport) // { // controllerReports.add(controllerReport); // } // }
import controllers.deadbolt.RestrictedResource; import models.deadbolt.reports.ControllerReport; import models.deadbolt.reports.MethodReport; import models.deadbolt.reports.ProjectReport; import play.Play; import play.mvc.Before; import play.mvc.Controller; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List;
if (Play.mode == Play.Mode.PROD) { error(404, "Page not found"); } } public static void report() { ProjectReport projectReport = new ProjectReport(); projectReport.projectName = Play.configuration.getProperty("application.name"); List<Class> controllers = Play.classloader.getAssignableClasses(Controller.class); for (Class controller : controllers) { ControllerReport controllerReport = getControllerReport(controller); projectReport.addControllerReport(controllerReport); } render(projectReport); } private static ControllerReport getControllerReport(Class controller) { ControllerReport controllerReport = new ControllerReport(controller.getCanonicalName()); Method[] methods = controller.getMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().equals(Controller.class)) {
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // // Path: app/models/deadbolt/reports/MethodReport.java // public class MethodReport // { // public final String name; // // public final List<String> dynamicChecks = new ArrayList<String>(); // // public final List<String> staticChecks = new ArrayList<String>(); // // public MethodReport(String name) // { // this.name = name; // } // // public void addStaticCheck(String staticCheck) // { // staticChecks.add(staticCheck); // } // // public void addDynamicCheck(String dynamicCheck) // { // staticChecks.add(dynamicCheck); // } // // } // // Path: app/models/deadbolt/reports/ProjectReport.java // public class ProjectReport // { // public String projectName; // // public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>(); // // public void addControllerReport(ControllerReport controllerReport) // { // controllerReports.add(controllerReport); // } // } // Path: app/controllers/deadbolt/reports/DeadboltReporter.java import controllers.deadbolt.RestrictedResource; import models.deadbolt.reports.ControllerReport; import models.deadbolt.reports.MethodReport; import models.deadbolt.reports.ProjectReport; import play.Play; import play.mvc.Before; import play.mvc.Controller; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; if (Play.mode == Play.Mode.PROD) { error(404, "Page not found"); } } public static void report() { ProjectReport projectReport = new ProjectReport(); projectReport.projectName = Play.configuration.getProperty("application.name"); List<Class> controllers = Play.classloader.getAssignableClasses(Controller.class); for (Class controller : controllers) { ControllerReport controllerReport = getControllerReport(controller); projectReport.addControllerReport(controllerReport); } render(projectReport); } private static ControllerReport getControllerReport(Class controller) { ControllerReport controllerReport = new ControllerReport(controller.getCanonicalName()); Method[] methods = controller.getMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().equals(Controller.class)) {
MethodReport methodReport = getMethodReport(method);
schaloner/deadbolt
app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java
// Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // }
import models.deadbolt.ExternalizedRestrictions;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be). */ public interface ExternalizedRestrictionsAccessor {
// Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java import models.deadbolt.ExternalizedRestrictions; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * @author Steve Chaloner (steve@objectify.be). */ public interface ExternalizedRestrictionsAccessor {
ExternalizedRestrictions getExternalizedRestrictions(String name);
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AccessControlPreferences.java
// Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // }
import model.AccessControlPreference; import model.AclUser; import play.mvc.Controller;
package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AccessControlPreferences extends AclController { public static void index() {
// Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // Path: samples-and-tests/acl/app/controllers/AccessControlPreferences.java import model.AccessControlPreference; import model.AclUser; import play.mvc.Controller; package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AccessControlPreferences extends AclController { public static void index() {
AclUser user = AclUser.getByUserName(getCurrentUserName());
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AccessControlPreferences.java
// Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // }
import model.AccessControlPreference; import model.AclUser; import play.mvc.Controller;
package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AccessControlPreferences extends AclController { public static void index() { AclUser user = AclUser.getByUserName(getCurrentUserName());
// Path: samples-and-tests/acl/app/model/AccessControlPreference.java // @Entity // public class AccessControlPreference extends Model // { // public enum AccessChain { FRIENDS, ANYONE }; // // @Enumerated(EnumType.STRING) // public AccessChain friendVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain statusVisibility = AccessChain.ANYONE; // // @Enumerated(EnumType.STRING) // public AccessChain photoVisibility = AccessChain.ANYONE; // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // Path: samples-and-tests/acl/app/controllers/AccessControlPreferences.java import model.AccessControlPreference; import model.AclUser; import play.mvc.Controller; package controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AccessControlPreferences extends AclController { public static void index() { AclUser user = AclUser.getByUserName(getCurrentUserName());
AccessControlPreference preference = user.accessControlPreference;
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/jobs/TestDataLoader.java
// Path: samples-and-tests/integration-with-secure/app/models/ApplicationRole.java // @Entity // public class ApplicationRole extends Model implements Role // { // @Required // public String name; // // public ApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static ApplicationRole getByName(String name) // { // return ApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // }
import models.ApplicationRole; import models.User; import play.jobs.Job; import play.jobs.OnApplicationStart;
/* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class TestDataLoader extends Job { @Override public void doJob() throws Exception {
// Path: samples-and-tests/integration-with-secure/app/models/ApplicationRole.java // @Entity // public class ApplicationRole extends Model implements Role // { // @Required // public String name; // // public ApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static ApplicationRole getByName(String name) // { // return ApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // Path: samples-and-tests/integration-with-secure/app/jobs/TestDataLoader.java import models.ApplicationRole; import models.User; import play.jobs.Job; import play.jobs.OnApplicationStart; /* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class TestDataLoader extends Job { @Override public void doJob() throws Exception {
if (ApplicationRole.getByName("superadmin") == null)
schaloner/deadbolt
samples-and-tests/integration-with-secure/app/jobs/TestDataLoader.java
// Path: samples-and-tests/integration-with-secure/app/models/ApplicationRole.java // @Entity // public class ApplicationRole extends Model implements Role // { // @Required // public String name; // // public ApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static ApplicationRole getByName(String name) // { // return ApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // }
import models.ApplicationRole; import models.User; import play.jobs.Job; import play.jobs.OnApplicationStart;
/* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class TestDataLoader extends Job { @Override public void doJob() throws Exception { if (ApplicationRole.getByName("superadmin") == null) { new ApplicationRole("superadmin").save(); } if (ApplicationRole.getByName("standard-user") == null) { new ApplicationRole("standard-user").save(); }
// Path: samples-and-tests/integration-with-secure/app/models/ApplicationRole.java // @Entity // public class ApplicationRole extends Model implements Role // { // @Required // public String name; // // public ApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static ApplicationRole getByName(String name) // { // return ApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/integration-with-secure/app/models/User.java // @Entity // public class User extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public ApplicationRole role; // // public User(String userName, // String fullName, // ApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // } // // public static User getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // @Override // public String toString() // { // return this.userName; // } // // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // } // Path: samples-and-tests/integration-with-secure/app/jobs/TestDataLoader.java import models.ApplicationRole; import models.User; import play.jobs.Job; import play.jobs.OnApplicationStart; /* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class TestDataLoader extends Job { @Override public void doJob() throws Exception { if (ApplicationRole.getByName("superadmin") == null) { new ApplicationRole("superadmin").save(); } if (ApplicationRole.getByName("standard-user") == null) { new ApplicationRole("standard-user").save(); }
if (User.getByUserName("steve") == null)
schaloner/deadbolt
samples-and-tests/content-types/app/models/MyRoleHolder.java
// Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import models.deadbolt.Role; import models.deadbolt.RoleHolder; import java.util.Arrays; import java.util.Collections; import java.util.List;
package models; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyRoleHolder implements RoleHolder {
// Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/content-types/app/models/MyRoleHolder.java import models.deadbolt.Role; import models.deadbolt.RoleHolder; import java.util.Arrays; import java.util.Collections; import java.util.List; package models; /** * @author Steve Chaloner (steve@objectify.be) */ public class MyRoleHolder implements RoleHolder {
public List<? extends Role> getRoles()
schaloner/deadbolt
app/models/deadbolt/reports/ProjectReport.java
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // }
import models.deadbolt.reports.ControllerReport; import java.util.ArrayList; import java.util.List;
package models.deadbolt.reports; /** * @author Steve Chaloner (steve@objectify.be) */ public class ProjectReport { public String projectName;
// Path: app/models/deadbolt/reports/ControllerReport.java // public class ControllerReport // { // public final String name; // // public final List<MethodReport> methodReports = new ArrayList<MethodReport>(); // // public ControllerReport(String name) // { // this.name = name; // } // // public void addMethodReport(MethodReport methodReport) // { // methodReports.add(methodReport); // } // } // Path: app/models/deadbolt/reports/ProjectReport.java import models.deadbolt.reports.ControllerReport; import java.util.ArrayList; import java.util.List; package models.deadbolt.reports; /** * @author Steve Chaloner (steve@objectify.be) */ public class ProjectReport { public String projectName;
public final List<ControllerReport> controllerReports = new ArrayList<ControllerReport>();
schaloner/deadbolt
samples-and-tests/acl/app/jobs/AclTestDataLoader.java
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // }
import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List;
/* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class AclTestDataLoader extends Job { @Override public void doJob() throws Exception { roles(); users(); defineRelationships(); content(); } private void roles() {
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // } // Path: samples-and-tests/acl/app/jobs/AclTestDataLoader.java import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List; /* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class AclTestDataLoader extends Job { @Override public void doJob() throws Exception { roles(); users(); defineRelationships(); content(); } private void roles() {
if (AclApplicationRole.getByName("standard-user") == null)
schaloner/deadbolt
samples-and-tests/acl/app/jobs/AclTestDataLoader.java
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // }
import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List;
/* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class AclTestDataLoader extends Job { @Override public void doJob() throws Exception { roles(); users(); defineRelationships(); content(); } private void roles() { if (AclApplicationRole.getByName("standard-user") == null) { new AclApplicationRole("standard-user").save(); } } private void users() {
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // } // Path: samples-and-tests/acl/app/jobs/AclTestDataLoader.java import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List; /* * Copyright 2010-2011 Steve Chaloner * * 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 jobs; /** * @author Steve Chaloner (steve@objectify.be) */ @OnApplicationStart public class AclTestDataLoader extends Job { @Override public void doJob() throws Exception { roles(); users(); defineRelationships(); content(); } private void roles() { if (AclApplicationRole.getByName("standard-user") == null) { new AclApplicationRole("standard-user").save(); } } private void users() {
if (AclUser.getByUserName("steve") == null)
schaloner/deadbolt
samples-and-tests/acl/app/jobs/AclTestDataLoader.java
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // }
import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List;
AclUser ansje = AclUser.getByUserName("ansje"); if (isEmpty(ansje.friends)) { ansje.addFriend(AclUser.getByUserName("christophe")); ansje.save(); } AclUser christophe = AclUser.getByUserName("christophe"); if (isEmpty(christophe.friends)) { christophe.addFriend(AclUser.getByUserName("steve")); christophe.save(); } } private void content() { List<AclUser> users = Arrays.asList(AclUser.getByUserName("steve"), AclUser.getByUserName("greet"), AclUser.getByUserName("christophe"), AclUser.getByUserName("ansje")); for (AclUser user : users) { if (isEmpty(user.photos)) { for (int i = 0; i < 5; i++) {
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // } // Path: samples-and-tests/acl/app/jobs/AclTestDataLoader.java import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List; AclUser ansje = AclUser.getByUserName("ansje"); if (isEmpty(ansje.friends)) { ansje.addFriend(AclUser.getByUserName("christophe")); ansje.save(); } AclUser christophe = AclUser.getByUserName("christophe"); if (isEmpty(christophe.friends)) { christophe.addFriend(AclUser.getByUserName("steve")); christophe.save(); } } private void content() { List<AclUser> users = Arrays.asList(AclUser.getByUserName("steve"), AclUser.getByUserName("greet"), AclUser.getByUserName("christophe"), AclUser.getByUserName("ansje")); for (AclUser user : users) { if (isEmpty(user.photos)) { for (int i = 0; i < 5; i++) {
Photo photo = new Photo();
schaloner/deadbolt
samples-and-tests/acl/app/jobs/AclTestDataLoader.java
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // }
import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List;
if (isEmpty(christophe.friends)) { christophe.addFriend(AclUser.getByUserName("steve")); christophe.save(); } } private void content() { List<AclUser> users = Arrays.asList(AclUser.getByUserName("steve"), AclUser.getByUserName("greet"), AclUser.getByUserName("christophe"), AclUser.getByUserName("ansje")); for (AclUser user : users) { if (isEmpty(user.photos)) { for (int i = 0; i < 5; i++) { Photo photo = new Photo(); photo.description = user.fullName + "'s photo #" + i; user.addPhoto(photo); } } if (isEmpty(user.statusUpdates)) { for (int i = 0; i < 5; i++) {
// Path: samples-and-tests/acl/app/model/AclApplicationRole.java // @Entity // public class AclApplicationRole extends Model implements Role // { // @Required // public String name; // // public AclApplicationRole(String name) // { // this.name = name; // } // // public String getRoleName() // { // return name; // } // // public static AclApplicationRole getByName(String name) // { // return AclApplicationRole.find("byName", name).first(); // } // // @Override // public String toString() // { // return this.name; // } // } // // Path: samples-and-tests/acl/app/model/AclUser.java // @Entity // public class AclUser extends Model implements RoleHolder // { // @Required // public String userName; // // public String fullName; // // @Required // @ManyToOne // public AclApplicationRole role; // // @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) // public List<AclUser> friends; // // @ManyToMany(cascade = CascadeType.ALL) // public List<Photo> photos; // // @ManyToMany(cascade = CascadeType.ALL) // public List<StatusUpdate> statusUpdates; // // @OneToOne(cascade = CascadeType.ALL) // public AccessControlPreference accessControlPreference; // // public AclUser(String userName, // String fullName, // AclApplicationRole role) // { // this.userName = userName; // this.fullName = fullName; // this.role = role; // this.accessControlPreference = new AccessControlPreference(); // } // // public static AclUser getByUserName(String userName) // { // return find("byUserName", userName).first(); // } // // public List<? extends Role> getRoles() // { // return Arrays.asList(role); // } // // public void addPhoto(Photo photo) // { // if (photos == null) // { // photos = new ArrayList<Photo>(); // } // photos.add(photo); // } // // public void addStatusUpdate(StatusUpdate statusUpdate) // { // if (statusUpdates == null) // { // statusUpdates = new ArrayList<StatusUpdate>(); // } // statusUpdates.add(statusUpdate); // } // // public void addFriend(AclUser friend) // { // if (friends == null) // { // friends = new ArrayList<AclUser>(); // } // friends.add(friend); // } // // public boolean isFriend(AclUser user) // { // return friends != null && friends.contains(user); // } // // @Override // public String toString() // { // return this.userName; // } // } // // Path: samples-and-tests/acl/app/model/Photo.java // @Entity // public class Photo extends Model // { // public String description; // } // // Path: samples-and-tests/acl/app/model/StatusUpdate.java // @Entity // public class StatusUpdate extends Model // { // public String status; // } // Path: samples-and-tests/acl/app/jobs/AclTestDataLoader.java import model.AclApplicationRole; import model.AclUser; import model.Photo; import model.StatusUpdate; import play.jobs.Job; import play.jobs.OnApplicationStart; import java.util.Arrays; import java.util.Collection; import java.util.List; if (isEmpty(christophe.friends)) { christophe.addFriend(AclUser.getByUserName("steve")); christophe.save(); } } private void content() { List<AclUser> users = Arrays.asList(AclUser.getByUserName("steve"), AclUser.getByUserName("greet"), AclUser.getByUserName("christophe"), AclUser.getByUserName("ansje")); for (AclUser user : users) { if (isEmpty(user.photos)) { for (int i = 0; i < 5; i++) { Photo photo = new Photo(); photo.description = user.fullName + "'s photo #" + i; user.addPhoto(photo); } } if (isEmpty(user.statusUpdates)) { for (int i = 0; i < 5; i++) {
StatusUpdate statusUpdate = new StatusUpdate();
schaloner/deadbolt
app/controllers/deadbolt/Deadbolt.java
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * Checks authorisation based on role names. * * @author Steve Chaloner (steve@objectify.be). */ public class Deadbolt extends Controller { private enum RestrictionType { NONE, DYNAMIC, STATIC, BASIC } public static final String DEADBOLT_HANDLER_KEY = "deadbolt.handler"; public static final String CACHE_USER_KEY = "deadbolt.cache-user-per-request"; public static final String CACHE_PER_REQUEST = "deadbolt.cache-user"; public static final String DEFAULT_RESPONSE_FORMAT = "deadbolt.default-response-format"; private static DeadboltHandler DEADBOLT_HANDLER; static { String handlerName = Play.configuration.getProperty(DEADBOLT_HANDLER_KEY); if (handlerName == null) { throw new ConfigurationException("deadbolt.handler must be defined"); } try { Class<DeadboltHandler> clazz = (Class<DeadboltHandler>)Class.forName(handlerName); DEADBOLT_HANDLER = clazz.newInstance(); } catch (Exception e) { throw new ConfigurationException(String.format("Unable to create DeadboltHandler instance: [%s]", e.getMessage())); } }
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/Deadbolt.java import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /* * Copyright 2010-2011 Steve Chaloner * * 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 controllers.deadbolt; /** * Checks authorisation based on role names. * * @author Steve Chaloner (steve@objectify.be). */ public class Deadbolt extends Controller { private enum RestrictionType { NONE, DYNAMIC, STATIC, BASIC } public static final String DEADBOLT_HANDLER_KEY = "deadbolt.handler"; public static final String CACHE_USER_KEY = "deadbolt.cache-user-per-request"; public static final String CACHE_PER_REQUEST = "deadbolt.cache-user"; public static final String DEFAULT_RESPONSE_FORMAT = "deadbolt.default-response-format"; private static DeadboltHandler DEADBOLT_HANDLER; static { String handlerName = Play.configuration.getProperty(DEADBOLT_HANDLER_KEY); if (handlerName == null) { throw new ConfigurationException("deadbolt.handler must be defined"); } try { Class<DeadboltHandler> clazz = (Class<DeadboltHandler>)Class.forName(handlerName); DEADBOLT_HANDLER = clazz.newInstance(); } catch (Exception e) { throw new ConfigurationException(String.format("Unable to create DeadboltHandler instance: [%s]", e.getMessage())); } }
private static RoleHolder getRoleHolder()
schaloner/deadbolt
app/controllers/deadbolt/Deadbolt.java
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
handleExternalRestrictions(roleHolder); } @Util static void handleRestrictedResources(RoleHolder roleHolder) throws Throwable { Unrestricted actionUnrestricted = getActionAnnotation(Unrestricted.class); if (actionUnrestricted == null) { RestrictedResource restrictedResource = getActionAnnotation(RestrictedResource.class); if (restrictedResource == null) { actionUnrestricted = getControllerAnnotation(Unrestricted.class); if (actionUnrestricted == null) { restrictedResource = getControllerInheritedAnnotation(RestrictedResource.class); } } if (restrictedResource != null) { RestrictedResourcesHandler restrictedResourcesHandler = DEADBOLT_HANDLER.getRestrictedResourcesHandler(); if (restrictedResourcesHandler == null) { Logger.fatal("A RestrictedResource is specified but no RestrictedResourcesHandler is available. Denying access to resource."); } else { String[] names = restrictedResource.name();
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/Deadbolt.java import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; handleExternalRestrictions(roleHolder); } @Util static void handleRestrictedResources(RoleHolder roleHolder) throws Throwable { Unrestricted actionUnrestricted = getActionAnnotation(Unrestricted.class); if (actionUnrestricted == null) { RestrictedResource restrictedResource = getActionAnnotation(RestrictedResource.class); if (restrictedResource == null) { actionUnrestricted = getControllerAnnotation(Unrestricted.class); if (actionUnrestricted == null) { restrictedResource = getControllerInheritedAnnotation(RestrictedResource.class); } } if (restrictedResource != null) { RestrictedResourcesHandler restrictedResourcesHandler = DEADBOLT_HANDLER.getRestrictedResourcesHandler(); if (restrictedResourcesHandler == null) { Logger.fatal("A RestrictedResource is specified but no RestrictedResourcesHandler is available. Denying access to resource."); } else { String[] names = restrictedResource.name();
AccessResult accessResult = restrictedResourcesHandler.checkAccess(names == null ? Collections.<String>emptyList() : Arrays.asList(names),
schaloner/deadbolt
app/controllers/deadbolt/Deadbolt.java
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
@Util static void handleExternalRestrictions(RoleHolder roleHolder) throws Throwable { Unrestricted actionUnrestricted = getActionAnnotation(Unrestricted.class); if (actionUnrestricted == null) { ExternalRestrictions externalRestrictions = getActionAnnotation(ExternalRestrictions.class); if (externalRestrictions == null) { actionUnrestricted = getControllerAnnotation(Unrestricted.class); if (actionUnrestricted == null) { externalRestrictions = getControllerInheritedAnnotation(ExternalRestrictions.class); } } if (externalRestrictions != null) { ExternalizedRestrictionsAccessor externalisedRestrictionsAccessor = DEADBOLT_HANDLER.getExternalizedRestrictionsAccessor(); boolean roleOk = false; if (externalisedRestrictionsAccessor == null) { Logger.fatal("@ExternalRestrictions are specified but no ExternalizedRestrictionsAccessor is available. Denying access to resource."); } else { for (String externalRestrictionTreeName : externalRestrictions.value()) {
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/Deadbolt.java import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @Util static void handleExternalRestrictions(RoleHolder roleHolder) throws Throwable { Unrestricted actionUnrestricted = getActionAnnotation(Unrestricted.class); if (actionUnrestricted == null) { ExternalRestrictions externalRestrictions = getActionAnnotation(ExternalRestrictions.class); if (externalRestrictions == null) { actionUnrestricted = getControllerAnnotation(Unrestricted.class); if (actionUnrestricted == null) { externalRestrictions = getControllerInheritedAnnotation(ExternalRestrictions.class); } } if (externalRestrictions != null) { ExternalizedRestrictionsAccessor externalisedRestrictionsAccessor = DEADBOLT_HANDLER.getExternalizedRestrictionsAccessor(); boolean roleOk = false; if (externalisedRestrictionsAccessor == null) { Logger.fatal("@ExternalRestrictions are specified but no ExternalizedRestrictionsAccessor is available. Denying access to resource."); } else { for (String externalRestrictionTreeName : externalRestrictions.value()) {
ExternalizedRestrictions externalizedRestrictions =
schaloner/deadbolt
app/controllers/deadbolt/Deadbolt.java
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
if (actionUnrestricted == null) { ExternalRestrictions externalRestrictions = getActionAnnotation(ExternalRestrictions.class); if (externalRestrictions == null) { actionUnrestricted = getControllerAnnotation(Unrestricted.class); if (actionUnrestricted == null) { externalRestrictions = getControllerInheritedAnnotation(ExternalRestrictions.class); } } if (externalRestrictions != null) { ExternalizedRestrictionsAccessor externalisedRestrictionsAccessor = DEADBOLT_HANDLER.getExternalizedRestrictionsAccessor(); boolean roleOk = false; if (externalisedRestrictionsAccessor == null) { Logger.fatal("@ExternalRestrictions are specified but no ExternalizedRestrictionsAccessor is available. Denying access to resource."); } else { for (String externalRestrictionTreeName : externalRestrictions.value()) { ExternalizedRestrictions externalizedRestrictions = externalisedRestrictionsAccessor.getExternalizedRestrictions(externalRestrictionTreeName); if (externalizedRestrictions != null) {
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/Deadbolt.java import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; if (actionUnrestricted == null) { ExternalRestrictions externalRestrictions = getActionAnnotation(ExternalRestrictions.class); if (externalRestrictions == null) { actionUnrestricted = getControllerAnnotation(Unrestricted.class); if (actionUnrestricted == null) { externalRestrictions = getControllerInheritedAnnotation(ExternalRestrictions.class); } } if (externalRestrictions != null) { ExternalizedRestrictionsAccessor externalisedRestrictionsAccessor = DEADBOLT_HANDLER.getExternalizedRestrictionsAccessor(); boolean roleOk = false; if (externalisedRestrictionsAccessor == null) { Logger.fatal("@ExternalRestrictions are specified but no ExternalizedRestrictionsAccessor is available. Denying access to resource."); } else { for (String externalRestrictionTreeName : externalRestrictions.value()) { ExternalizedRestrictions externalizedRestrictions = externalisedRestrictionsAccessor.getExternalizedRestrictions(externalRestrictionTreeName); if (externalizedRestrictions != null) {
List<ExternalizedRestriction> restrictions = externalizedRestrictions.getExternalisedRestrictions();
schaloner/deadbolt
app/controllers/deadbolt/Deadbolt.java
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
{ String defaultResponseFormat = Play.configuration.getProperty(DEFAULT_RESPONSE_FORMAT); if (!isEmpty(defaultResponseFormat)) { responseFormat = defaultResponseFormat; } } if (!isEmpty(responseFormat)) { request.format = responseFormat; } DEADBOLT_HANDLER.onAccessFailure(controllerClassName); } /** * Checks if the current user has all of the specified roles. * * @param roleHolder the object requiring authorisation * @param roleNames the role names * @return true iff the current user has all of the specified roles */ public static boolean hasAllRoles(RoleHolder roleHolder, String[] roleNames) { boolean hasRole = false; if (roleHolder != null) {
// Path: app/models/deadbolt/AccessResult.java // public enum AccessResult // { // ALLOWED, // DENIED, // NOT_SPECIFIED // } // // Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // // Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: app/controllers/deadbolt/Deadbolt.java import java.util.List; import java.util.Map; import models.deadbolt.AccessResult; import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.Logger; import play.Play; import play.exceptions.ConfigurationException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; { String defaultResponseFormat = Play.configuration.getProperty(DEFAULT_RESPONSE_FORMAT); if (!isEmpty(defaultResponseFormat)) { responseFormat = defaultResponseFormat; } } if (!isEmpty(responseFormat)) { request.format = responseFormat; } DEADBOLT_HANDLER.onAccessFailure(controllerClassName); } /** * Checks if the current user has all of the specified roles. * * @param roleHolder the object requiring authorisation * @param roleNames the role names * @return true iff the current user has all of the specified roles */ public static boolean hasAllRoles(RoleHolder roleHolder, String[] roleNames) { boolean hasRole = false; if (roleHolder != null) {
List<? extends Role> roles = roleHolder.getRoles();
schaloner/deadbolt
samples-and-tests/unrestricted-samples/app/deadbolt/MyExternalizedRestrictions.java
// Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // }
import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
/* * Copyright 2010-2011 Steve Chaloner * * 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 deadbolt; /** * @author Steve Chaloner (steve@objectify.be). */ public class MyExternalizedRestrictions implements ExternalizedRestrictions {
// Path: app/models/deadbolt/ExternalizedRestriction.java // public interface ExternalizedRestriction // { // /** // * Gets the role names required to get by this restriction. // * // * @return the role names // */ // List<String> getRoleNames(); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // Path: samples-and-tests/unrestricted-samples/app/deadbolt/MyExternalizedRestrictions.java import models.deadbolt.ExternalizedRestriction; import models.deadbolt.ExternalizedRestrictions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* * Copyright 2010-2011 Steve Chaloner * * 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 deadbolt; /** * @author Steve Chaloner (steve@objectify.be). */ public class MyExternalizedRestrictions implements ExternalizedRestrictions {
private final List<ExternalizedRestriction> restrictions = new ArrayList<ExternalizedRestriction>();
schaloner/deadbolt
samples-and-tests/acl/app/model/AclUser.java
// Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // }
import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.data.validation.Required; import play.db.jpa.Model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
@ManyToOne public AclApplicationRole role; @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) public List<AclUser> friends; @ManyToMany(cascade = CascadeType.ALL) public List<Photo> photos; @ManyToMany(cascade = CascadeType.ALL) public List<StatusUpdate> statusUpdates; @OneToOne(cascade = CascadeType.ALL) public AccessControlPreference accessControlPreference; public AclUser(String userName, String fullName, AclApplicationRole role) { this.userName = userName; this.fullName = fullName; this.role = role; this.accessControlPreference = new AccessControlPreference(); } public static AclUser getByUserName(String userName) { return find("byUserName", userName).first(); }
// Path: app/models/deadbolt/Role.java // public interface Role // { // /** // * The name of the role. // * // * @return the role name // */ // String getRoleName(); // } // // Path: app/models/deadbolt/RoleHolder.java // public interface RoleHolder // { // /** // * A list of {@link Role}s held by the role holder. // * // * @return a list of roles // */ // List<? extends Role> getRoles(); // } // Path: samples-and-tests/acl/app/model/AclUser.java import models.deadbolt.Role; import models.deadbolt.RoleHolder; import play.data.validation.Required; import play.db.jpa.Model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @ManyToOne public AclApplicationRole role; @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH}) public List<AclUser> friends; @ManyToMany(cascade = CascadeType.ALL) public List<Photo> photos; @ManyToMany(cascade = CascadeType.ALL) public List<StatusUpdate> statusUpdates; @OneToOne(cascade = CascadeType.ALL) public AccessControlPreference accessControlPreference; public AclUser(String userName, String fullName, AclApplicationRole role) { this.userName = userName; this.fullName = fullName; this.role = role; this.accessControlPreference = new AccessControlPreference(); } public static AclUser getByUserName(String userName) { return find("byUserName", userName).first(); }
public List<? extends Role> getRoles()
schaloner/deadbolt
samples-and-tests/unrestricted-samples/app/deadbolt/MyExternalizedRestrictionsAccessor.java
// Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // }
import controllers.deadbolt.ExternalizedRestrictionsAccessor; import models.deadbolt.ExternalizedRestrictions; import java.util.HashMap; import java.util.Map;
/* * Copyright 2010-2011 Steve Chaloner * * 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 deadbolt; /** * @author Steve Chaloner (steve@objectify.be). */ public class MyExternalizedRestrictionsAccessor implements ExternalizedRestrictionsAccessor {
// Path: app/controllers/deadbolt/ExternalizedRestrictionsAccessor.java // public interface ExternalizedRestrictionsAccessor // { // ExternalizedRestrictions getExternalizedRestrictions(String name); // } // // Path: app/models/deadbolt/ExternalizedRestrictions.java // public interface ExternalizedRestrictions // { // /** // * Gets all the {@link ExternalizedRestriction}s associated with a target. // * // * @return // */ // List<ExternalizedRestriction> getExternalisedRestrictions(); // } // Path: samples-and-tests/unrestricted-samples/app/deadbolt/MyExternalizedRestrictionsAccessor.java import controllers.deadbolt.ExternalizedRestrictionsAccessor; import models.deadbolt.ExternalizedRestrictions; import java.util.HashMap; import java.util.Map; /* * Copyright 2010-2011 Steve Chaloner * * 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 deadbolt; /** * @author Steve Chaloner (steve@objectify.be). */ public class MyExternalizedRestrictionsAccessor implements ExternalizedRestrictionsAccessor {
private final Map<String, ExternalizedRestrictions> restrictions = new HashMap<String, ExternalizedRestrictions>();
orbisgis/poly2tri.java
poly2tri-core/src/main/java/org/poly2tri/triangulation/delaunay/DelaunayTriangle.java
// Path: poly2tri-core/src/main/java/org/poly2tri/triangulation/TriangulationPoint.java // public abstract class TriangulationPoint extends Point // { // // List of edges this point constitutes an upper ending point (CDT) // private ArrayList<DTSweepConstraint> edges; // // @Override // public String toString() // { // return "[" + getX() + "," + getY() + "]"; // } // // public abstract double getX(); // public abstract double getY(); // public abstract double getZ(); // // public abstract float getXf(); // public abstract float getYf(); // public abstract float getZf(); // // public abstract void set( double x, double y, double z ); // // public ArrayList<DTSweepConstraint> getEdges() // { // return edges; // } // // public void addEdge( DTSweepConstraint e ) // { // if( edges == null ) // { // edges = new ArrayList<DTSweepConstraint>(); // } // edges.add( e ); // } // // public boolean hasEdges() // { // return edges != null; // } // // /** // * @param p - edge destination point // * @return the edge from this point to given point // */ // public DTSweepConstraint getEdge( TriangulationPoint p ) // { // for( DTSweepConstraint c : edges ) // { // if( c.p == p ) // { // return c; // } // } // return null; // } // // public boolean equals(Object obj) // { // if( obj instanceof TriangulationPoint ) // { // TriangulationPoint p = (TriangulationPoint)obj; // return getX() == p.getX() && getY() == p.getY(); // } // return super.equals( obj ); // } // // public int hashCode() // { // long bits = java.lang.Double.doubleToLongBits(getX()); // bits ^= java.lang.Double.doubleToLongBits(getY()) * 31; // return (((int) bits) ^ ((int) (bits >> 32))); // } // // // /** // * Replace points in ptList for all equals object in uniquePts. // * @param uniquePts Map of triangulation points // * @param ptList Point list, updated, but always the same size. // */ // public static void mergeInstances(Map<TriangulationPoint, TriangulationPoint> uniquePts, List<TriangulationPoint> ptList) { // for(int idPoint = 0; idPoint < ptList.size(); idPoint++) { // TriangulationPoint pt = ptList.get(idPoint); // TriangulationPoint uniquePt = uniquePts.get(pt); // if(uniquePt == null) { // uniquePts.put(pt, pt); // } else { // // Duplicate point // ptList.set(idPoint, uniquePt); // } // } // } // }
import java.util.ArrayList; import java.util.Arrays; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; import org.poly2tri.triangulation.point.TPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.delaunay; public class DelaunayTriangle { private final static Logger logger = LoggerFactory.getLogger( DelaunayTriangle.class ); /** Neighbor pointers */ public final DelaunayTriangle[] neighbors = new DelaunayTriangle[3]; /** Flags to determine if an edge is a Constrained edge */ public final boolean[] cEdge = new boolean[] { false, false, false }; /** Flags to determine if an edge is a Delauney edge */ public final boolean[] dEdge = new boolean[] { false, false, false }; /** Has this triangle been marked as an interior triangle? */ protected boolean interior = false;
// Path: poly2tri-core/src/main/java/org/poly2tri/triangulation/TriangulationPoint.java // public abstract class TriangulationPoint extends Point // { // // List of edges this point constitutes an upper ending point (CDT) // private ArrayList<DTSweepConstraint> edges; // // @Override // public String toString() // { // return "[" + getX() + "," + getY() + "]"; // } // // public abstract double getX(); // public abstract double getY(); // public abstract double getZ(); // // public abstract float getXf(); // public abstract float getYf(); // public abstract float getZf(); // // public abstract void set( double x, double y, double z ); // // public ArrayList<DTSweepConstraint> getEdges() // { // return edges; // } // // public void addEdge( DTSweepConstraint e ) // { // if( edges == null ) // { // edges = new ArrayList<DTSweepConstraint>(); // } // edges.add( e ); // } // // public boolean hasEdges() // { // return edges != null; // } // // /** // * @param p - edge destination point // * @return the edge from this point to given point // */ // public DTSweepConstraint getEdge( TriangulationPoint p ) // { // for( DTSweepConstraint c : edges ) // { // if( c.p == p ) // { // return c; // } // } // return null; // } // // public boolean equals(Object obj) // { // if( obj instanceof TriangulationPoint ) // { // TriangulationPoint p = (TriangulationPoint)obj; // return getX() == p.getX() && getY() == p.getY(); // } // return super.equals( obj ); // } // // public int hashCode() // { // long bits = java.lang.Double.doubleToLongBits(getX()); // bits ^= java.lang.Double.doubleToLongBits(getY()) * 31; // return (((int) bits) ^ ((int) (bits >> 32))); // } // // // /** // * Replace points in ptList for all equals object in uniquePts. // * @param uniquePts Map of triangulation points // * @param ptList Point list, updated, but always the same size. // */ // public static void mergeInstances(Map<TriangulationPoint, TriangulationPoint> uniquePts, List<TriangulationPoint> ptList) { // for(int idPoint = 0; idPoint < ptList.size(); idPoint++) { // TriangulationPoint pt = ptList.get(idPoint); // TriangulationPoint uniquePt = uniquePts.get(pt); // if(uniquePt == null) { // uniquePts.put(pt, pt); // } else { // // Duplicate point // ptList.set(idPoint, uniquePt); // } // } // } // } // Path: poly2tri-core/src/main/java/org/poly2tri/triangulation/delaunay/DelaunayTriangle.java import java.util.ArrayList; import java.util.Arrays; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; import org.poly2tri.triangulation.point.TPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.delaunay; public class DelaunayTriangle { private final static Logger logger = LoggerFactory.getLogger( DelaunayTriangle.class ); /** Neighbor pointers */ public final DelaunayTriangle[] neighbors = new DelaunayTriangle[3]; /** Flags to determine if an edge is a Constrained edge */ public final boolean[] cEdge = new boolean[] { false, false, false }; /** Flags to determine if an edge is a Delauney edge */ public final boolean[] dEdge = new boolean[] { false, false, false }; /** Has this triangle been marked as an interior triangle? */ protected boolean interior = false;
public final TriangulationPoint[] points = new TriangulationPoint[3];
orbisgis/poly2tri.java
poly2tri-examples-geotools/src/main/java/org/poly2tri/examples/geotools/WGS84GeodeticTransform.java
// Path: poly2tri-core/src/main/java/org/poly2tri/triangulation/TriangulationPoint.java // public abstract class TriangulationPoint extends Point // { // // List of edges this point constitutes an upper ending point (CDT) // private ArrayList<DTSweepConstraint> edges; // // @Override // public String toString() // { // return "[" + getX() + "," + getY() + "]"; // } // // public abstract double getX(); // public abstract double getY(); // public abstract double getZ(); // // public abstract float getXf(); // public abstract float getYf(); // public abstract float getZf(); // // public abstract void set( double x, double y, double z ); // // public ArrayList<DTSweepConstraint> getEdges() // { // return edges; // } // // public void addEdge( DTSweepConstraint e ) // { // if( edges == null ) // { // edges = new ArrayList<DTSweepConstraint>(); // } // edges.add( e ); // } // // public boolean hasEdges() // { // return edges != null; // } // // /** // * @param p - edge destination point // * @return the edge from this point to given point // */ // public DTSweepConstraint getEdge( TriangulationPoint p ) // { // for( DTSweepConstraint c : edges ) // { // if( c.p == p ) // { // return c; // } // } // return null; // } // // public boolean equals(Object obj) // { // if( obj instanceof TriangulationPoint ) // { // TriangulationPoint p = (TriangulationPoint)obj; // return getX() == p.getX() && getY() == p.getY(); // } // return super.equals( obj ); // } // // public int hashCode() // { // long bits = java.lang.Double.doubleToLongBits(getX()); // bits ^= java.lang.Double.doubleToLongBits(getY()) * 31; // return (((int) bits) ^ ((int) (bits >> 32))); // } // // // /** // * Replace points in ptList for all equals object in uniquePts. // * @param uniquePts Map of triangulation points // * @param ptList Point list, updated, but always the same size. // */ // public static void mergeInstances(Map<TriangulationPoint, TriangulationPoint> uniquePts, List<TriangulationPoint> ptList) { // for(int idPoint = 0; idPoint < ptList.size(); idPoint++) { // TriangulationPoint pt = ptList.get(idPoint); // TriangulationPoint uniquePt = uniquePts.get(pt); // if(uniquePt == null) { // uniquePts.put(pt, pt); // } else { // // Duplicate point // ptList.set(idPoint, uniquePt); // } // } // } // }
import java.util.List; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.transform.coordinate.CoordinateTransform; import org.poly2tri.triangulation.TriangulationPoint;
package org.poly2tri.examples.geotools; /** * Converts a Point with Longitude,Latitude,Altitude representation to cartesian coordinates * * TODO: * * WGS-84 * The relation between Cartesian coordinates (X,Y,Z) and the curvilinear ones (lat,lon,h) is: X = (N+h) * cos(lat) * cos(lon) Y = (N+h) * cos(lat) * sin(lon) Z = (N*(1-e2)+h) * sin(lat) where N = prime vertical radius of curvature = a/sqrt(1-e2*sin(lat)^2) e2 = first eccentricity of the reference ellipsoid = 1 -b^2/a^2 a = major semi-axis of reference ellipsoid = 6378137.000 m for WGS-84 b = minor semi-axis of reference ellipsoid = 6356752.314 m for WGS-84 * http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif * @author Thomas Åhlén, thahlen@gmail.com */ public class WGS84GeodeticTransform implements CoordinateTransform { private final static double PI_div180 = Math.PI/180; private double _radius = 1; public WGS84GeodeticTransform( double radius ) { _radius = radius; } // @Override // public double toX( TriangulationPoint p ) // { // return _radius*Math.cos( PI_div180*p.getY() )*Math.cos( PI_div180*p.getX() ); // } // // @Override // public double toY( TriangulationPoint p ) // { // return _radius*Math.sin( PI_div180*p.getY() ); // } // // @Override // public double toZ( TriangulationPoint p ) // { // return -_radius*Math.cos( PI_div180*p.getY() )*Math.sin( PI_div180*p.getX() ); // } // // @Override // public float toXf( TriangulationPoint p ) // { // return (float)toX(p); // } // // @Override // public float toYf( TriangulationPoint p ) // { // return (float)toY(p); // } // // @Override // public float toZf( TriangulationPoint p ) // { // return (float)toZ(p); // }
// Path: poly2tri-core/src/main/java/org/poly2tri/triangulation/TriangulationPoint.java // public abstract class TriangulationPoint extends Point // { // // List of edges this point constitutes an upper ending point (CDT) // private ArrayList<DTSweepConstraint> edges; // // @Override // public String toString() // { // return "[" + getX() + "," + getY() + "]"; // } // // public abstract double getX(); // public abstract double getY(); // public abstract double getZ(); // // public abstract float getXf(); // public abstract float getYf(); // public abstract float getZf(); // // public abstract void set( double x, double y, double z ); // // public ArrayList<DTSweepConstraint> getEdges() // { // return edges; // } // // public void addEdge( DTSweepConstraint e ) // { // if( edges == null ) // { // edges = new ArrayList<DTSweepConstraint>(); // } // edges.add( e ); // } // // public boolean hasEdges() // { // return edges != null; // } // // /** // * @param p - edge destination point // * @return the edge from this point to given point // */ // public DTSweepConstraint getEdge( TriangulationPoint p ) // { // for( DTSweepConstraint c : edges ) // { // if( c.p == p ) // { // return c; // } // } // return null; // } // // public boolean equals(Object obj) // { // if( obj instanceof TriangulationPoint ) // { // TriangulationPoint p = (TriangulationPoint)obj; // return getX() == p.getX() && getY() == p.getY(); // } // return super.equals( obj ); // } // // public int hashCode() // { // long bits = java.lang.Double.doubleToLongBits(getX()); // bits ^= java.lang.Double.doubleToLongBits(getY()) * 31; // return (((int) bits) ^ ((int) (bits >> 32))); // } // // // /** // * Replace points in ptList for all equals object in uniquePts. // * @param uniquePts Map of triangulation points // * @param ptList Point list, updated, but always the same size. // */ // public static void mergeInstances(Map<TriangulationPoint, TriangulationPoint> uniquePts, List<TriangulationPoint> ptList) { // for(int idPoint = 0; idPoint < ptList.size(); idPoint++) { // TriangulationPoint pt = ptList.get(idPoint); // TriangulationPoint uniquePt = uniquePts.get(pt); // if(uniquePt == null) { // uniquePts.put(pt, pt); // } else { // // Duplicate point // ptList.set(idPoint, uniquePt); // } // } // } // } // Path: poly2tri-examples-geotools/src/main/java/org/poly2tri/examples/geotools/WGS84GeodeticTransform.java import java.util.List; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.transform.coordinate.CoordinateTransform; import org.poly2tri.triangulation.TriangulationPoint; package org.poly2tri.examples.geotools; /** * Converts a Point with Longitude,Latitude,Altitude representation to cartesian coordinates * * TODO: * * WGS-84 * The relation between Cartesian coordinates (X,Y,Z) and the curvilinear ones (lat,lon,h) is: X = (N+h) * cos(lat) * cos(lon) Y = (N+h) * cos(lat) * sin(lon) Z = (N*(1-e2)+h) * sin(lat) where N = prime vertical radius of curvature = a/sqrt(1-e2*sin(lat)^2) e2 = first eccentricity of the reference ellipsoid = 1 -b^2/a^2 a = major semi-axis of reference ellipsoid = 6378137.000 m for WGS-84 b = minor semi-axis of reference ellipsoid = 6356752.314 m for WGS-84 * http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif * @author Thomas Åhlén, thahlen@gmail.com */ public class WGS84GeodeticTransform implements CoordinateTransform { private final static double PI_div180 = Math.PI/180; private double _radius = 1; public WGS84GeodeticTransform( double radius ) { _radius = radius; } // @Override // public double toX( TriangulationPoint p ) // { // return _radius*Math.cos( PI_div180*p.getY() )*Math.cos( PI_div180*p.getX() ); // } // // @Override // public double toY( TriangulationPoint p ) // { // return _radius*Math.sin( PI_div180*p.getY() ); // } // // @Override // public double toZ( TriangulationPoint p ) // { // return -_radius*Math.cos( PI_div180*p.getY() )*Math.sin( PI_div180*p.getX() ); // } // // @Override // public float toXf( TriangulationPoint p ) // { // return (float)toX(p); // } // // @Override // public float toYf( TriangulationPoint p ) // { // return (float)toY(p); // } // // @Override // public float toZf( TriangulationPoint p ) // { // return (float)toZ(p); // }
public void transform( TriangulationPoint p, TriangulationPoint store )
patrickfav/Dali
dali/src/main/java/at/favre/lib/dali/builder/ABuilder.java
// Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // }
import at.favre.lib.dali.blur.IBlur;
package at.favre.lib.dali.builder; /** * Created by PatrickF on 29.05.2014. */ public abstract class ABuilder { public static class Data { public int blurRadius = BuilderDefaults.BLUR_RADIUS;
// Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // } // Path: dali/src/main/java/at/favre/lib/dali/builder/ABuilder.java import at.favre.lib.dali.blur.IBlur; package at.favre.lib.dali.builder; /** * Created by PatrickF on 29.05.2014. */ public abstract class ABuilder { public static class Data { public int blurRadius = BuilderDefaults.BLUR_RADIUS;
public IBlur blurAlgorithm;
patrickfav/Dali
dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptBox3x3Blur.java
// Path: dali/src/main/java/at/favre/lib/dali/blur/BlurKernels.java // public final class BlurKernels { // private BlurKernels() { // } // // public static final float[] GAUSSIAN_5x5 = new float[]{ // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0219f, 0.0983f, 0.1621f, 0.0983f, 0.0219f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f // }; // // public static final float[] BOX_5x5 = new float[]{ // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.0425f, 0.05f, 0.0425f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f // }; // // public static final float[] BOX_3x3 = new float[]{ // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.13f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f // }; // } // // Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // }
import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import androidx.renderscript.ScriptIntrinsicConvolve3x3; import at.favre.lib.dali.blur.BlurKernels; import at.favre.lib.dali.blur.IBlur;
package at.favre.lib.dali.blur.algorithms; /** * This is a convolve matrix based blur algorithms powered by Renderscript's ScriptIntrinsicConvolve class. This uses a box kernel. * Instead of radius it uses passes, so a radius parameter of 16 makes the convolve algorithm applied 16 times onto the image. */ public class RenderScriptBox3x3Blur implements IBlur { private RenderScript rs; public RenderScriptBox3x3Blur(RenderScript rs) { this.rs = rs; } @Override public Bitmap blur(int radius, Bitmap bitmapOriginal) { Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); final Allocation output = Allocation.createTyped(rs, input.getType()); final ScriptIntrinsicConvolve3x3 script = ScriptIntrinsicConvolve3x3.create(rs, Element.U8_4(rs));
// Path: dali/src/main/java/at/favre/lib/dali/blur/BlurKernels.java // public final class BlurKernels { // private BlurKernels() { // } // // public static final float[] GAUSSIAN_5x5 = new float[]{ // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0219f, 0.0983f, 0.1621f, 0.0983f, 0.0219f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f // }; // // public static final float[] BOX_5x5 = new float[]{ // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.0425f, 0.05f, 0.0425f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f // }; // // public static final float[] BOX_3x3 = new float[]{ // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.13f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f // }; // } // // Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // } // Path: dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptBox3x3Blur.java import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import androidx.renderscript.ScriptIntrinsicConvolve3x3; import at.favre.lib.dali.blur.BlurKernels; import at.favre.lib.dali.blur.IBlur; package at.favre.lib.dali.blur.algorithms; /** * This is a convolve matrix based blur algorithms powered by Renderscript's ScriptIntrinsicConvolve class. This uses a box kernel. * Instead of radius it uses passes, so a radius parameter of 16 makes the convolve algorithm applied 16 times onto the image. */ public class RenderScriptBox3x3Blur implements IBlur { private RenderScript rs; public RenderScriptBox3x3Blur(RenderScript rs) { this.rs = rs; } @Override public Bitmap blur(int radius, Bitmap bitmapOriginal) { Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); final Allocation output = Allocation.createTyped(rs, input.getType()); final ScriptIntrinsicConvolve3x3 script = ScriptIntrinsicConvolve3x3.create(rs, Element.U8_4(rs));
script.setCoefficients(BlurKernels.BOX_3x3);
patrickfav/Dali
dali/src/main/java/at/favre/lib/dali/blur/EBlurAlgorithm.java
// Path: dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptGaussianBlur.java // public class RenderScriptGaussianBlur implements IBlur { // private RenderScript rs; // // public RenderScriptGaussianBlur(RenderScript rs) { // this.rs = rs; // } // // @Override // public Bitmap blur(int radius, Bitmap bitmapOriginal) { // final Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); // final Allocation output = Allocation.createTyped(rs, input.getType()); // final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // script.setRadius(radius); // script.setInput(input); // script.forEach(output); // output.copyTo(bitmapOriginal); // return bitmapOriginal; // } // }
import androidx.renderscript.RenderScript; import java.util.ArrayList; import java.util.List; import at.favre.lib.dali.blur.algorithms.RenderScriptGaussianBlur;
package at.favre.lib.dali.blur; /** * Enum of all supported algorithms * * @author pfavre */ public enum EBlurAlgorithm { RS_GAUSS_FAST, RS_BOX_5x5, RS_GAUSS_5x5, RS_STACKBLUR, STACKBLUR, GAUSS_FAST, BOX_BLUR, NONE; public static List<EBlurAlgorithm> getAllAlgorithms() { List<EBlurAlgorithm> algorithms = new ArrayList<EBlurAlgorithm>(); for (EBlurAlgorithm algorithm : values()) { if (!algorithm.equals(NONE)) { algorithms.add(algorithm); } } return algorithms; } public static IBlur createDefaultBlur(RenderScript rs) {
// Path: dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptGaussianBlur.java // public class RenderScriptGaussianBlur implements IBlur { // private RenderScript rs; // // public RenderScriptGaussianBlur(RenderScript rs) { // this.rs = rs; // } // // @Override // public Bitmap blur(int radius, Bitmap bitmapOriginal) { // final Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); // final Allocation output = Allocation.createTyped(rs, input.getType()); // final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // script.setRadius(radius); // script.setInput(input); // script.forEach(output); // output.copyTo(bitmapOriginal); // return bitmapOriginal; // } // } // Path: dali/src/main/java/at/favre/lib/dali/blur/EBlurAlgorithm.java import androidx.renderscript.RenderScript; import java.util.ArrayList; import java.util.List; import at.favre.lib.dali.blur.algorithms.RenderScriptGaussianBlur; package at.favre.lib.dali.blur; /** * Enum of all supported algorithms * * @author pfavre */ public enum EBlurAlgorithm { RS_GAUSS_FAST, RS_BOX_5x5, RS_GAUSS_5x5, RS_STACKBLUR, STACKBLUR, GAUSS_FAST, BOX_BLUR, NONE; public static List<EBlurAlgorithm> getAllAlgorithms() { List<EBlurAlgorithm> algorithms = new ArrayList<EBlurAlgorithm>(); for (EBlurAlgorithm algorithm : values()) { if (!algorithm.equals(NONE)) { algorithms.add(algorithm); } } return algorithms; } public static IBlur createDefaultBlur(RenderScript rs) {
return new RenderScriptGaussianBlur(rs);
patrickfav/Dali
dali/src/main/java/at/favre/lib/dali/builder/PerformanceProfiler.java
// Path: dali/src/main/java/at/favre/lib/dali/util/BenchmarkUtil.java // public final class BenchmarkUtil { // private static final DecimalFormat format = new DecimalFormat("#.0"); // private static final String fileSeperator = ";"; // // static { // format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH)); // format.setRoundingMode(RoundingMode.HALF_UP); // } // // private BenchmarkUtil() { // } // // public static long elapsedRealTimeNanos() { // if (Build.VERSION.SDK_INT >= 17) { // return SystemClock.elapsedRealtimeNanos(); // } // return SystemClock.elapsedRealtime() * 1000000L; // } // // public static String formatNum(double number) { // return format.format(number); // } // // public static String formatNum(double number, String formatString) { // final DecimalFormat format = new DecimalFormat(formatString); // format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH)); // format.setRoundingMode(RoundingMode.HALF_UP); // return format.format(number); // } // // public static String getScalingUnitByteSize(int byteSize) { // double scaledByteSize = (double) byteSize; // String unit = "byte"; // // if (scaledByteSize < 1024) { // return formatNum(scaledByteSize, "0.##") + unit; // } else { // unit = "KiB"; // scaledByteSize /= 1024d; // // if (scaledByteSize < 1024) { // return formatNum(scaledByteSize, "0.##") + unit; // } else { // unit = "MiB"; // scaledByteSize /= 1024d; // if (scaledByteSize < 1024) { // return formatNum(scaledByteSize, "0.##") + unit; // } else { // unit = "GiB"; // scaledByteSize /= 1024d; // return formatNum(scaledByteSize, "0.##") + unit; // } // } // } // } // // public static String getCurrentTime() { // SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss.SSS", Locale.getDefault()); // return sdf.format(new Date()); // } // }
import android.util.Log; import java.util.ArrayList; import java.util.List; import at.favre.lib.dali.util.BenchmarkUtil;
package at.favre.lib.dali.builder; /** * A simple Profiler that helps in measuring parts of code. * <p> * This will use nano seconds (if possible with SDK) */ public class PerformanceProfiler { private static final String TAG = PerformanceProfiler.class.getSimpleName(); private String description; private List<Duration> durations; private boolean isActivated; public PerformanceProfiler(String description) { this(description, true); } /** * @param description describes the task * @param isActivated if this is false, every call to a method will do exactly nothing to * avoid to have unnecessary overhead */ public PerformanceProfiler(String description, boolean isActivated) { this.description = description; this.durations = new ArrayList<Duration>(); this.isActivated = isActivated; } /** * Start a task. The id is needed to end the task * * @param id * @param taskName */ public void startTask(int id, String taskName) { if (isActivated) {
// Path: dali/src/main/java/at/favre/lib/dali/util/BenchmarkUtil.java // public final class BenchmarkUtil { // private static final DecimalFormat format = new DecimalFormat("#.0"); // private static final String fileSeperator = ";"; // // static { // format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH)); // format.setRoundingMode(RoundingMode.HALF_UP); // } // // private BenchmarkUtil() { // } // // public static long elapsedRealTimeNanos() { // if (Build.VERSION.SDK_INT >= 17) { // return SystemClock.elapsedRealtimeNanos(); // } // return SystemClock.elapsedRealtime() * 1000000L; // } // // public static String formatNum(double number) { // return format.format(number); // } // // public static String formatNum(double number, String formatString) { // final DecimalFormat format = new DecimalFormat(formatString); // format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH)); // format.setRoundingMode(RoundingMode.HALF_UP); // return format.format(number); // } // // public static String getScalingUnitByteSize(int byteSize) { // double scaledByteSize = (double) byteSize; // String unit = "byte"; // // if (scaledByteSize < 1024) { // return formatNum(scaledByteSize, "0.##") + unit; // } else { // unit = "KiB"; // scaledByteSize /= 1024d; // // if (scaledByteSize < 1024) { // return formatNum(scaledByteSize, "0.##") + unit; // } else { // unit = "MiB"; // scaledByteSize /= 1024d; // if (scaledByteSize < 1024) { // return formatNum(scaledByteSize, "0.##") + unit; // } else { // unit = "GiB"; // scaledByteSize /= 1024d; // return formatNum(scaledByteSize, "0.##") + unit; // } // } // } // } // // public static String getCurrentTime() { // SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss.SSS", Locale.getDefault()); // return sdf.format(new Date()); // } // } // Path: dali/src/main/java/at/favre/lib/dali/builder/PerformanceProfiler.java import android.util.Log; import java.util.ArrayList; import java.util.List; import at.favre.lib.dali.util.BenchmarkUtil; package at.favre.lib.dali.builder; /** * A simple Profiler that helps in measuring parts of code. * <p> * This will use nano seconds (if possible with SDK) */ public class PerformanceProfiler { private static final String TAG = PerformanceProfiler.class.getSimpleName(); private String description; private List<Duration> durations; private boolean isActivated; public PerformanceProfiler(String description) { this(description, true); } /** * @param description describes the task * @param isActivated if this is false, every call to a method will do exactly nothing to * avoid to have unnecessary overhead */ public PerformanceProfiler(String description, boolean isActivated) { this.description = description; this.durations = new ArrayList<Duration>(); this.isActivated = isActivated; } /** * Start a task. The id is needed to end the task * * @param id * @param taskName */ public void startTask(int id, String taskName) { if (isActivated) {
durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));
patrickfav/Dali
dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptGaussian5x5Blur.java
// Path: dali/src/main/java/at/favre/lib/dali/blur/BlurKernels.java // public final class BlurKernels { // private BlurKernels() { // } // // public static final float[] GAUSSIAN_5x5 = new float[]{ // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0219f, 0.0983f, 0.1621f, 0.0983f, 0.0219f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f // }; // // public static final float[] BOX_5x5 = new float[]{ // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.0425f, 0.05f, 0.0425f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f // }; // // public static final float[] BOX_3x3 = new float[]{ // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.13f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f // }; // } // // Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // }
import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import androidx.renderscript.ScriptIntrinsicConvolve5x5; import at.favre.lib.dali.blur.BlurKernels; import at.favre.lib.dali.blur.IBlur;
package at.favre.lib.dali.blur.algorithms; /** * This is a convolve matrix based blur algorithms powered by Renderscript's ScriptIntrinsicConvolve class. This uses a gaussian kernel. * Instead of radius it uses passes, so a radius parameter of 16 makes the convolve algorithm applied 16 times onto the image. */ public class RenderScriptGaussian5x5Blur implements IBlur { private RenderScript rs; public RenderScriptGaussian5x5Blur(RenderScript rs) { this.rs = rs; } @Override public Bitmap blur(int radius, Bitmap bitmapOriginal) { Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); final Allocation output = Allocation.createTyped(rs, input.getType()); final ScriptIntrinsicConvolve5x5 script = ScriptIntrinsicConvolve5x5.create(rs, Element.U8_4(rs));
// Path: dali/src/main/java/at/favre/lib/dali/blur/BlurKernels.java // public final class BlurKernels { // private BlurKernels() { // } // // public static final float[] GAUSSIAN_5x5 = new float[]{ // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0219f, 0.0983f, 0.1621f, 0.0983f, 0.0219f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f // }; // // public static final float[] BOX_5x5 = new float[]{ // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.0425f, 0.05f, 0.0425f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f // }; // // public static final float[] BOX_3x3 = new float[]{ // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.13f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f // }; // } // // Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // } // Path: dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptGaussian5x5Blur.java import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import androidx.renderscript.ScriptIntrinsicConvolve5x5; import at.favre.lib.dali.blur.BlurKernels; import at.favre.lib.dali.blur.IBlur; package at.favre.lib.dali.blur.algorithms; /** * This is a convolve matrix based blur algorithms powered by Renderscript's ScriptIntrinsicConvolve class. This uses a gaussian kernel. * Instead of radius it uses passes, so a radius parameter of 16 makes the convolve algorithm applied 16 times onto the image. */ public class RenderScriptGaussian5x5Blur implements IBlur { private RenderScript rs; public RenderScriptGaussian5x5Blur(RenderScript rs) { this.rs = rs; } @Override public Bitmap blur(int radius, Bitmap bitmapOriginal) { Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); final Allocation output = Allocation.createTyped(rs, input.getType()); final ScriptIntrinsicConvolve5x5 script = ScriptIntrinsicConvolve5x5.create(rs, Element.U8_4(rs));
script.setCoefficients(BlurKernels.GAUSSIAN_5x5);
patrickfav/Dali
dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptBox5x5Blur.java
// Path: dali/src/main/java/at/favre/lib/dali/blur/BlurKernels.java // public final class BlurKernels { // private BlurKernels() { // } // // public static final float[] GAUSSIAN_5x5 = new float[]{ // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0219f, 0.0983f, 0.1621f, 0.0983f, 0.0219f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f // }; // // public static final float[] BOX_5x5 = new float[]{ // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.0425f, 0.05f, 0.0425f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f // }; // // public static final float[] BOX_3x3 = new float[]{ // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.13f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f // }; // } // // Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // }
import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import androidx.renderscript.ScriptIntrinsicConvolve5x5; import at.favre.lib.dali.blur.BlurKernels; import at.favre.lib.dali.blur.IBlur;
package at.favre.lib.dali.blur.algorithms; /** * This is a convolve matrix based blur algorithms powered by Renderscript's ScriptIntrinsicConvolve class. This uses a box kernel. * Instead of radius it uses passes, so a radius parameter of 16 makes the convolve algorithm applied 16 times onto the image. */ public class RenderScriptBox5x5Blur implements IBlur { private RenderScript rs; public RenderScriptBox5x5Blur(RenderScript rs) { this.rs = rs; } @Override public Bitmap blur(int radius, Bitmap bitmapOriginal) { Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); final Allocation output = Allocation.createTyped(rs, input.getType()); final ScriptIntrinsicConvolve5x5 script = ScriptIntrinsicConvolve5x5.create(rs, Element.U8_4(rs));
// Path: dali/src/main/java/at/favre/lib/dali/blur/BlurKernels.java // public final class BlurKernels { // private BlurKernels() { // } // // public static final float[] GAUSSIAN_5x5 = new float[]{ // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0219f, 0.0983f, 0.1621f, 0.0983f, 0.0219f, // 0.0133f, 0.0596f, 0.0983f, 0.0596f, 0.0133f, // 0.0030f, 0.0133f, 0.0219f, 0.0133f, 0.0030f // }; // // public static final float[] BOX_5x5 = new float[]{ // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.0425f, 0.05f, 0.0425f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f, // 0.04f, 0.04f, 0.04f, 0.04f, 0.04f // }; // // public static final float[] BOX_3x3 = new float[]{ // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.13f, 0.111111111111111111111111112f, // 0.111111111111111111111111112f, 0.111111111111111111111111112f, 0.111111111111111111111111112f // }; // } // // Path: dali/src/main/java/at/favre/lib/dali/blur/IBlur.java // public interface IBlur { // //threshold for live blurring // int MS_THRESHOLD_FOR_SMOOTH = 16; // // /** // * Takes a bitmap and blurs it with the given blur radius. This will NOT copy the original // * but reuses it, so if this instance will be used somewhere else, manual copying is needed. // * // * @param radius blurradius, keep in mind some algorithms don't take all values (e.g. ScriptIntrinsicBlur will only take 1-25) // * @param original // * @return blurred original bitmap // */ // Bitmap blur(int radius, Bitmap original); // } // Path: dali/src/main/java/at/favre/lib/dali/blur/algorithms/RenderScriptBox5x5Blur.java import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import androidx.renderscript.ScriptIntrinsicConvolve5x5; import at.favre.lib.dali.blur.BlurKernels; import at.favre.lib.dali.blur.IBlur; package at.favre.lib.dali.blur.algorithms; /** * This is a convolve matrix based blur algorithms powered by Renderscript's ScriptIntrinsicConvolve class. This uses a box kernel. * Instead of radius it uses passes, so a radius parameter of 16 makes the convolve algorithm applied 16 times onto the image. */ public class RenderScriptBox5x5Blur implements IBlur { private RenderScript rs; public RenderScriptBox5x5Blur(RenderScript rs) { this.rs = rs; } @Override public Bitmap blur(int radius, Bitmap bitmapOriginal) { Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); final Allocation output = Allocation.createTyped(rs, input.getType()); final ScriptIntrinsicConvolve5x5 script = ScriptIntrinsicConvolve5x5.create(rs, Element.U8_4(rs));
script.setCoefficients(BlurKernels.BOX_5x5);
ooyala/Ooyala-AdobeCQ
core/src/main/java/com/siteworx/cq5/ooyala/client/OoyalaPostClient.java
// Path: core/src/main/java/com/siteworx/cq5/ooyala/client/request/OoyalaPutRequest.java // public class OoyalaPutRequest extends OoyalaRequest { // // private JSONObject body; // // public OoyalaPutRequest(OoyalaApiCredential credentials) { // super(credentials, HTTPMethod.PUT, "/v2/assets"); // } // // public OoyalaPutRequest(OoyalaApiCredential credentials, String pathSuffix) { // super (credentials, HTTPMethod.PUT, "/v2/assets/" +pathSuffix); // } // // public JSONObject getBody() { // return body; // } // // public void setBody(JSONObject body) { // this.body = body; // } // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map.Entry; import java.util.SortedMap; import javax.ws.rs.core.MediaType; import org.apache.sling.commons.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.siteworx.cq5.ooyala.client.request.OoyalaPostRequest; import com.siteworx.cq5.ooyala.client.request.OoyalaPutRequest; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.core.util.Base64;
package com.siteworx.cq5.ooyala.client; /** * Copyright (c) 2012, Ooyala, Inc. * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * Ooyala REST API client. The public methods in this class are thread-safe. * * @author leonardo@siteworx.com * @author rboll@siteworx.com * */ public class OoyalaPostClient extends OoyalaClient { private static final Logger log = LoggerFactory.getLogger(OoyalaClient.class); private final MessageDigest digest; private final Client client; /** * Constructs the Ooyala Client. * * @throws NoSuchAlgorithmException Throws an exception if SHA-256 algorithm is not found by MessageDigest. */ public OoyalaPostClient(){ try { digest = MessageDigest.getInstance("SHA-256"); client = Client.create(); client.setConnectTimeout(15000);//15 second timeout client.setReadTimeout(60000);//60 second timeout } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * * @param request * @return * @throws OoyalaClientException */
// Path: core/src/main/java/com/siteworx/cq5/ooyala/client/request/OoyalaPutRequest.java // public class OoyalaPutRequest extends OoyalaRequest { // // private JSONObject body; // // public OoyalaPutRequest(OoyalaApiCredential credentials) { // super(credentials, HTTPMethod.PUT, "/v2/assets"); // } // // public OoyalaPutRequest(OoyalaApiCredential credentials, String pathSuffix) { // super (credentials, HTTPMethod.PUT, "/v2/assets/" +pathSuffix); // } // // public JSONObject getBody() { // return body; // } // // public void setBody(JSONObject body) { // this.body = body; // } // } // Path: core/src/main/java/com/siteworx/cq5/ooyala/client/OoyalaPostClient.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map.Entry; import java.util.SortedMap; import javax.ws.rs.core.MediaType; import org.apache.sling.commons.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.siteworx.cq5.ooyala.client.request.OoyalaPostRequest; import com.siteworx.cq5.ooyala.client.request.OoyalaPutRequest; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.core.util.Base64; package com.siteworx.cq5.ooyala.client; /** * Copyright (c) 2012, Ooyala, Inc. * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * Ooyala REST API client. The public methods in this class are thread-safe. * * @author leonardo@siteworx.com * @author rboll@siteworx.com * */ public class OoyalaPostClient extends OoyalaClient { private static final Logger log = LoggerFactory.getLogger(OoyalaClient.class); private final MessageDigest digest; private final Client client; /** * Constructs the Ooyala Client. * * @throws NoSuchAlgorithmException Throws an exception if SHA-256 algorithm is not found by MessageDigest. */ public OoyalaPostClient(){ try { digest = MessageDigest.getInstance("SHA-256"); client = Client.create(); client.setConnectTimeout(15000);//15 second timeout client.setReadTimeout(60000);//60 second timeout } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * * @param request * @return * @throws OoyalaClientException */
public String request(OoyalaPutRequest request) throws OoyalaClientException {
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FieldDescription.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/FormsUtil.java // public class FormsUtil { // // private FormsUtil() { // // no instances // } // // /** // * Filter the element name for unallowed characters. // * @param nodeName The name of the element // * @return Filtered named // */ // public static String filterElementName(String nodeName) { // final StringBuilder sb = new StringBuilder(); // char lastAdded = 0; // // for(int i=0; i < nodeName.length(); i++) { // final char c = nodeName.charAt(i); // char toAdd = c; // // if (FormsConstants.ALLOWED_NAME_CHARS.indexOf(c) < 0) { // if (lastAdded == FormsConstants.REPLACEMENT_CHAR) { // // do not add several _ in a row // continue; // } // toAdd = FormsConstants.REPLACEMENT_CHAR; // // } else if(i == 0 && Character.isDigit(c)) { // sb.append(FormsConstants.REPLACEMENT_CHAR); // } // // sb.append(toAdd); // lastAdded = toAdd; // } // // if (sb.length()==0) { // sb.append(FormsConstants.REPLACEMENT_CHAR); // } // // return sb.toString(); // } // }
import com.day.cq.wcm.foundation.forms.impl.FormsUtil; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap;
/* * Copyright 1997-2009 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package com.day.cq.wcm.foundation.forms; /** * A description of a form field as it is later used in the html * form. * A field component usually maps to a single field description, * however compound fields like an address field map to * several field descriptions. * * The field description is used mostly during validation as it * contains all necessary information. * * Field descriptions can be maintained from the {@link FieldHelper}. * @since 5.3 */ public class FieldDescription { /** Field name. */ private String name; /** Is this field required? */ private boolean required = false; /** The message which is displayed if a required field is not set. */ private String requiredMsg; /** Optional constraint type */ private String constraintType; /** The message which is displayed if the constraint is not met. */ private String constraintMsg; /** Is this a read only field? */ private boolean readOnly = false; /** Is this a private field? */ private boolean privateField = false; /** Is this a multi value field? */ private boolean multiValue = false; /** The associated resource. */ private final Resource fieldResource; /** * Construct a new field description for a field resource. * @param rsrc */ public FieldDescription(final Resource rsrc) { this.fieldResource = rsrc; } /** * Construct a new field description for a field resource * and set the name property. * @param rsrc The resource * @param name The field name. */ public FieldDescription(final Resource rsrc, final String name) { this.fieldResource = rsrc; this.name = name; } public void update(final Resource rsrc) { final ValueMap props = ResourceUtil.getValueMap(rsrc); this.required = props.get(FormsConstants.ELEMENT_PROPERTY_REQUIRED, Boolean.FALSE); this.readOnly = props.get(FormsConstants.ELEMENT_PROPERTY_READ_ONLY, Boolean.FALSE); String name = props.get(FormsConstants.ELEMENT_PROPERTY_NAME, ""); if ( name.length() == 0 ) { name = ResourceUtil.getName(rsrc);
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/FormsUtil.java // public class FormsUtil { // // private FormsUtil() { // // no instances // } // // /** // * Filter the element name for unallowed characters. // * @param nodeName The name of the element // * @return Filtered named // */ // public static String filterElementName(String nodeName) { // final StringBuilder sb = new StringBuilder(); // char lastAdded = 0; // // for(int i=0; i < nodeName.length(); i++) { // final char c = nodeName.charAt(i); // char toAdd = c; // // if (FormsConstants.ALLOWED_NAME_CHARS.indexOf(c) < 0) { // if (lastAdded == FormsConstants.REPLACEMENT_CHAR) { // // do not add several _ in a row // continue; // } // toAdd = FormsConstants.REPLACEMENT_CHAR; // // } else if(i == 0 && Character.isDigit(c)) { // sb.append(FormsConstants.REPLACEMENT_CHAR); // } // // sb.append(toAdd); // lastAdded = toAdd; // } // // if (sb.length()==0) { // sb.append(FormsConstants.REPLACEMENT_CHAR); // } // // return sb.toString(); // } // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FieldDescription.java import com.day.cq.wcm.foundation.forms.impl.FormsUtil; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; /* * Copyright 1997-2009 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package com.day.cq.wcm.foundation.forms; /** * A description of a form field as it is later used in the html * form. * A field component usually maps to a single field description, * however compound fields like an address field map to * several field descriptions. * * The field description is used mostly during validation as it * contains all necessary information. * * Field descriptions can be maintained from the {@link FieldHelper}. * @since 5.3 */ public class FieldDescription { /** Field name. */ private String name; /** Is this field required? */ private boolean required = false; /** The message which is displayed if a required field is not set. */ private String requiredMsg; /** Optional constraint type */ private String constraintType; /** The message which is displayed if the constraint is not met. */ private String constraintMsg; /** Is this a read only field? */ private boolean readOnly = false; /** Is this a private field? */ private boolean privateField = false; /** Is this a multi value field? */ private boolean multiValue = false; /** The associated resource. */ private final Resource fieldResource; /** * Construct a new field description for a field resource. * @param rsrc */ public FieldDescription(final Resource rsrc) { this.fieldResource = rsrc; } /** * Construct a new field description for a field resource * and set the name property. * @param rsrc The resource * @param name The field name. */ public FieldDescription(final Resource rsrc, final String name) { this.fieldResource = rsrc; this.name = name; } public void update(final Resource rsrc) { final ValueMap props = ResourceUtil.getValueMap(rsrc); this.required = props.get(FormsConstants.ELEMENT_PROPERTY_REQUIRED, Boolean.FALSE); this.readOnly = props.get(FormsConstants.ELEMENT_PROPERTY_READ_ONLY, Boolean.FALSE); String name = props.get(FormsConstants.ELEMENT_PROPERTY_NAME, ""); if ( name.length() == 0 ) { name = ResourceUtil.getName(rsrc);
name = FormsUtil.filterElementName(name);
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/ValidationHelper.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/JspSlingHttpServletResponseWrapper.java // public class JspSlingHttpServletResponseWrapper extends SlingHttpServletResponseWrapper { // // // The original JspWriter of the wrapped response // private final JspWriter jspWriter; // // // The PrintWriter returned by the getWriter method. Wraps jspWriter // private final PrintWriter printWriter; // // public JspSlingHttpServletResponseWrapper(final SlingHttpServletResponse response, // final JspWriter writer) { // super(response); // // this.jspWriter = writer; // this.printWriter = new PrintWriter(this.jspWriter); // } // // /** // * Returns the writer for this response wrapper. // */ // public PrintWriter getWriter() { // return this.printWriter; // } // // /** // * Throws an <code>IllegalStateException</code> as this wrapper only // * supports writers. // */ // public ServletOutputStream getOutputStream() { // throw new IllegalStateException(); // } // // /** // * Resets the buffer of the JspWriter underlying the writer of this // * instance. // */ // public void resetBuffer() { // try { // this.jspWriter.clearBuffer(); // } catch (IOException ignore) { // // don't care // } // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspWriter; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.JspSlingHttpServletResponseWrapper; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper;
} return true; } /** * Convenience method to check the constraint of a form element. * @param request * @param resource The form element resource. * @deprecated Use {@link FieldHelper#checkConstraint(SlingHttpServletRequest, SlingHttpServletResponse, FieldDescription)} */ @Deprecated public static void checkConstraint(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final Resource resource) throws IOException, ServletException { final ValueMap properties = ResourceUtil.getValueMap(resource); final String name = FormsHelper.getParameterName(resource); final String value = request.getParameter(name); final boolean isEmpty = (value == null || value.trim().length() == 0); // we evaluate the constraint only if the field is not null if ( !isEmpty ) { // additional constraint? final String constraint = properties.get(FormsConstants.ELEMENT_PROPERTY_CONSTRAINT_TYPE, ""); if ( constraint.length() > 0 ) { String rt = constraint; if ( constraint.indexOf('/') == -1) { rt = FormsConstants.RT_FORM_CONSTRAINT + "s/" + rt; }
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/JspSlingHttpServletResponseWrapper.java // public class JspSlingHttpServletResponseWrapper extends SlingHttpServletResponseWrapper { // // // The original JspWriter of the wrapped response // private final JspWriter jspWriter; // // // The PrintWriter returned by the getWriter method. Wraps jspWriter // private final PrintWriter printWriter; // // public JspSlingHttpServletResponseWrapper(final SlingHttpServletResponse response, // final JspWriter writer) { // super(response); // // this.jspWriter = writer; // this.printWriter = new PrintWriter(this.jspWriter); // } // // /** // * Returns the writer for this response wrapper. // */ // public PrintWriter getWriter() { // return this.printWriter; // } // // /** // * Throws an <code>IllegalStateException</code> as this wrapper only // * supports writers. // */ // public ServletOutputStream getOutputStream() { // throw new IllegalStateException(); // } // // /** // * Resets the buffer of the JspWriter underlying the writer of this // * instance. // */ // public void resetBuffer() { // try { // this.jspWriter.clearBuffer(); // } catch (IOException ignore) { // // don't care // } // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/ValidationHelper.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspWriter; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.JspSlingHttpServletResponseWrapper; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper; } return true; } /** * Convenience method to check the constraint of a form element. * @param request * @param resource The form element resource. * @deprecated Use {@link FieldHelper#checkConstraint(SlingHttpServletRequest, SlingHttpServletResponse, FieldDescription)} */ @Deprecated public static void checkConstraint(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final Resource resource) throws IOException, ServletException { final ValueMap properties = ResourceUtil.getValueMap(resource); final String name = FormsHelper.getParameterName(resource); final String value = request.getParameter(name); final boolean isEmpty = (value == null || value.trim().length() == 0); // we evaluate the constraint only if the field is not null if ( !isEmpty ) { // additional constraint? final String constraint = properties.get(FormsConstants.ELEMENT_PROPERTY_CONSTRAINT_TYPE, ""); if ( constraint.length() > 0 ) { String rt = constraint; if ( constraint.indexOf('/') == -1) { rt = FormsConstants.RT_FORM_CONSTRAINT + "s/" + rt; }
final Resource includeResource = new ResourceWrapper(resource, rt, FormsConstants.RST_FORM_CONSTRAINT);
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/ValidationHelper.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/JspSlingHttpServletResponseWrapper.java // public class JspSlingHttpServletResponseWrapper extends SlingHttpServletResponseWrapper { // // // The original JspWriter of the wrapped response // private final JspWriter jspWriter; // // // The PrintWriter returned by the getWriter method. Wraps jspWriter // private final PrintWriter printWriter; // // public JspSlingHttpServletResponseWrapper(final SlingHttpServletResponse response, // final JspWriter writer) { // super(response); // // this.jspWriter = writer; // this.printWriter = new PrintWriter(this.jspWriter); // } // // /** // * Returns the writer for this response wrapper. // */ // public PrintWriter getWriter() { // return this.printWriter; // } // // /** // * Throws an <code>IllegalStateException</code> as this wrapper only // * supports writers. // */ // public ServletOutputStream getOutputStream() { // throw new IllegalStateException(); // } // // /** // * Resets the buffer of the JspWriter underlying the writer of this // * instance. // */ // public void resetBuffer() { // try { // this.jspWriter.clearBuffer(); // } catch (IOException ignore) { // // don't care // } // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspWriter; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.JspSlingHttpServletResponseWrapper; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper;
final String name = FormsHelper.getParameterName(resource); return "document.forms[\"" + StringEscapeUtils.escapeEcmaScript(formId) + "\"]" + ".elements[\"" + StringEscapeUtils.escapeEcmaScript(name) + "\"]"; } /** * Write java script client code for a constraint check. * @deprecated Use {@link FieldHelper#writeClientConstraintCheck(SlingHttpServletRequest, SlingHttpServletResponse, FieldDescription)} */ @Deprecated public static void writeConstraintCheck(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final Resource resource, final JspWriter out) throws IOException, ServletException { final ValueMap properties = ResourceUtil.getValueMap(resource); // additional constraint? final String constraint = properties.get(FormsConstants.ELEMENT_PROPERTY_CONSTRAINT_TYPE, ""); if ( constraint.length() > 0 ) { final String qualifier = getFormElementQualifier(request, resource); out.print("if (!cq5forms_isEmpty("); out.print(qualifier); out.print(")){"); String rt = constraint; if ( constraint.indexOf('/') == -1) { rt = FormsConstants.RT_FORM_CONSTRAINT + "s/" + rt; } final Resource includeResource = new ResourceWrapper(resource, rt, FormsConstants.RST_FORM_CONSTRAINT);
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/JspSlingHttpServletResponseWrapper.java // public class JspSlingHttpServletResponseWrapper extends SlingHttpServletResponseWrapper { // // // The original JspWriter of the wrapped response // private final JspWriter jspWriter; // // // The PrintWriter returned by the getWriter method. Wraps jspWriter // private final PrintWriter printWriter; // // public JspSlingHttpServletResponseWrapper(final SlingHttpServletResponse response, // final JspWriter writer) { // super(response); // // this.jspWriter = writer; // this.printWriter = new PrintWriter(this.jspWriter); // } // // /** // * Returns the writer for this response wrapper. // */ // public PrintWriter getWriter() { // return this.printWriter; // } // // /** // * Throws an <code>IllegalStateException</code> as this wrapper only // * supports writers. // */ // public ServletOutputStream getOutputStream() { // throw new IllegalStateException(); // } // // /** // * Resets the buffer of the JspWriter underlying the writer of this // * instance. // */ // public void resetBuffer() { // try { // this.jspWriter.clearBuffer(); // } catch (IOException ignore) { // // don't care // } // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/ValidationHelper.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspWriter; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.JspSlingHttpServletResponseWrapper; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper; final String name = FormsHelper.getParameterName(resource); return "document.forms[\"" + StringEscapeUtils.escapeEcmaScript(formId) + "\"]" + ".elements[\"" + StringEscapeUtils.escapeEcmaScript(name) + "\"]"; } /** * Write java script client code for a constraint check. * @deprecated Use {@link FieldHelper#writeClientConstraintCheck(SlingHttpServletRequest, SlingHttpServletResponse, FieldDescription)} */ @Deprecated public static void writeConstraintCheck(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final Resource resource, final JspWriter out) throws IOException, ServletException { final ValueMap properties = ResourceUtil.getValueMap(resource); // additional constraint? final String constraint = properties.get(FormsConstants.ELEMENT_PROPERTY_CONSTRAINT_TYPE, ""); if ( constraint.length() > 0 ) { final String qualifier = getFormElementQualifier(request, resource); out.print("if (!cq5forms_isEmpty("); out.print(qualifier); out.print(")){"); String rt = constraint; if ( constraint.indexOf('/') == -1) { rt = FormsConstants.RT_FORM_CONSTRAINT + "s/" + rt; } final Resource includeResource = new ResourceWrapper(resource, rt, FormsConstants.RST_FORM_CONSTRAINT);
FormsHelper.includeResource(request, new JspSlingHttpServletResponseWrapper(response, out), includeResource, FormsConstants.SCRIPT_CLIENT_VALIDATION);
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/test/java/com/day/cq/wcm/foundation/forms/FormResourceEditTest.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FormResourceEdit.java // public static class CommonAndPartial { // /** // * Common values, present in all multi-value properties. // */ // public Set<String> common = new HashSet<String>(); // /** // * Partial values, present only in one or a few multi-value properties, // * but not in all. // */ // public Set<String> partial = new HashSet<String>(); // }
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceMetadata; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.FormResourceEdit.CommonAndPartial;
/* * Copyright 1997-2011 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package com.day.cq.wcm.foundation.forms; public class FormResourceEditTest extends TestCase { private static final String PN_TEST = "test"; public void testCommonAndPartial() { // basic test with 2 resources List<Resource> resources = new ArrayList<Resource>(); resources.add(getResourceWithMultiValue(PN_TEST, "a", "b", "c")); resources.add(getResourceWithMultiValue(PN_TEST, "b", "c", "d"));
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FormResourceEdit.java // public static class CommonAndPartial { // /** // * Common values, present in all multi-value properties. // */ // public Set<String> common = new HashSet<String>(); // /** // * Partial values, present only in one or a few multi-value properties, // * but not in all. // */ // public Set<String> partial = new HashSet<String>(); // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/test/java/com/day/cq/wcm/foundation/forms/FormResourceEditTest.java import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceMetadata; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.FormResourceEdit.CommonAndPartial; /* * Copyright 1997-2011 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package com.day.cq.wcm.foundation.forms; public class FormResourceEditTest extends TestCase { private static final String PN_TEST = "test"; public void testCommonAndPartial() { // basic test with 2 resources List<Resource> resources = new ArrayList<Resource>(); resources.add(getResourceWithMultiValue(PN_TEST, "a", "b", "c")); resources.add(getResourceWithMultiValue(PN_TEST, "b", "c", "d"));
CommonAndPartial result = FormResourceEdit.getCommonAndPartialMultiValues(resources, PN_TEST);
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/impl/Rewriter.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/External.java // public static enum Limit { // // NO("no"), // HOST("host"), // OFF("off"); // // private final String value; // // private Limit(String value) { // this.value = value; // } // // @Override // public String toString() { // return value; // } // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.PushbackInputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.day.cq.rewriter.htmlparser.AttributeList; import com.day.cq.rewriter.htmlparser.DocumentHandler; import com.day.cq.rewriter.htmlparser.HtmlParser; import com.day.cq.wcm.foundation.External.Limit; import com.day.text.Text;
/* * $Id: Rewriter.java 60840 2009-11-13 16:39:48Z cziegele $ * * Copyright (c) 1997-2003 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package com.day.cq.wcm.foundation.impl; /** * Central rewriter that rewrites HTML pages to pass over its own rewriting * engine. */ public class Rewriter implements DocumentHandler { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(Rewriter.class); /** * Path to current page. */ private final String pagePath; /** * Path to current resource. */ private final String resourcePath; /** * Target to show. */ private final String target; /** * Reserved parameter name for target URL. */ private final String targetParamName; /** * Limit, one of {@link Limit#NO}, {@link Limit#HOST}, {@link Limit#OFF}. */
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/External.java // public static enum Limit { // // NO("no"), // HOST("host"), // OFF("off"); // // private final String value; // // private Limit(String value) { // this.value = value; // } // // @Override // public String toString() { // return value; // } // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/impl/Rewriter.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.PushbackInputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.day.cq.rewriter.htmlparser.AttributeList; import com.day.cq.rewriter.htmlparser.DocumentHandler; import com.day.cq.rewriter.htmlparser.HtmlParser; import com.day.cq.wcm.foundation.External.Limit; import com.day.text.Text; /* * $Id: Rewriter.java 60840 2009-11-13 16:39:48Z cziegele $ * * Copyright (c) 1997-2003 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package com.day.cq.wcm.foundation.impl; /** * Central rewriter that rewrites HTML pages to pass over its own rewriting * engine. */ public class Rewriter implements DocumentHandler { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(Rewriter.class); /** * Path to current page. */ private final String pagePath; /** * Path to current resource. */ private final String resourcePath; /** * Target to show. */ private final String target; /** * Reserved parameter name for target URL. */ private final String targetParamName; /** * Limit, one of {@link Limit#NO}, {@link Limit#HOST}, {@link Limit#OFF}. */
private Limit limit = Limit.NO;
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FieldHelper.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/FormsHandlingResponse.java // public class FormsHandlingResponse extends SlingHttpServletResponseWrapper { // // private ServletOutputStream nullstream; // private PrintWriter nullwriter; // // public FormsHandlingResponse(SlingHttpServletResponse wrappedResponse) { // super(wrappedResponse); // } // // @Override // public PrintWriter getWriter() { // if (nullwriter == null) { // nullwriter = new PrintWriter(getOutputStream()); // } // return nullwriter; // } // // @Override // public ServletOutputStream getOutputStream() { // if (nullstream == null) { // nullstream = new ServletOutputStream() { // // @Override // public void write(int b) { // // noop // } // // @Override // public void write(byte[] b) { // // noop // } // // @Override // public void write(byte[] b, int off, int len) // { // // noop // } // // @Override // public void flush() { // // noop // } // // @Override // public void close() { // // noop // } // }; // } // return nullstream; // } // // @Override // public void flushBuffer() { // // noop // } // // @Override // public void reset() { // // noop // } // // @Override // public void resetBuffer() { // // noop // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.FormsHandlingResponse; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper;
out.write(getConstraintMessage(desc, request)); out.write("', i); return false;}}} else {" + "if (!cq5forms_regcheck(obj.value, "); out.write(regexp); out.write(")) {" + "cq5forms_showMsg('"); out.write(StringEscapeUtils.escapeEcmaScript(FormsHelper.getFormId(request))); out.write("','"); out.write(StringEscapeUtils.escapeEcmaScript(desc.getName())); out.write("','"); out.write(StringEscapeUtils.escapeEcmaScript(getConstraintMessage(desc, request))); out.write("'); return false;}}}"); } /** * Write the client java script code to check a constraint on * form submit. */ public static void writeClientConstraintCheck(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final FieldDescription desc) throws IOException, ServletException { if ( desc.getConstraintType() != null ) { final PrintWriter out = response.getWriter(); final String qualifier = getClientFieldQualifier(request, desc); out.write("if (!cq5forms_isEmpty("); out.write(qualifier); out.write(")){"); try { request.setAttribute(ATTR_DESC, desc);
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/FormsHandlingResponse.java // public class FormsHandlingResponse extends SlingHttpServletResponseWrapper { // // private ServletOutputStream nullstream; // private PrintWriter nullwriter; // // public FormsHandlingResponse(SlingHttpServletResponse wrappedResponse) { // super(wrappedResponse); // } // // @Override // public PrintWriter getWriter() { // if (nullwriter == null) { // nullwriter = new PrintWriter(getOutputStream()); // } // return nullwriter; // } // // @Override // public ServletOutputStream getOutputStream() { // if (nullstream == null) { // nullstream = new ServletOutputStream() { // // @Override // public void write(int b) { // // noop // } // // @Override // public void write(byte[] b) { // // noop // } // // @Override // public void write(byte[] b, int off, int len) // { // // noop // } // // @Override // public void flush() { // // noop // } // // @Override // public void close() { // // noop // } // }; // } // return nullstream; // } // // @Override // public void flushBuffer() { // // noop // } // // @Override // public void reset() { // // noop // } // // @Override // public void resetBuffer() { // // noop // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FieldHelper.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.FormsHandlingResponse; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper; out.write(getConstraintMessage(desc, request)); out.write("', i); return false;}}} else {" + "if (!cq5forms_regcheck(obj.value, "); out.write(regexp); out.write(")) {" + "cq5forms_showMsg('"); out.write(StringEscapeUtils.escapeEcmaScript(FormsHelper.getFormId(request))); out.write("','"); out.write(StringEscapeUtils.escapeEcmaScript(desc.getName())); out.write("','"); out.write(StringEscapeUtils.escapeEcmaScript(getConstraintMessage(desc, request))); out.write("'); return false;}}}"); } /** * Write the client java script code to check a constraint on * form submit. */ public static void writeClientConstraintCheck(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final FieldDescription desc) throws IOException, ServletException { if ( desc.getConstraintType() != null ) { final PrintWriter out = response.getWriter(); final String qualifier = getClientFieldQualifier(request, desc); out.write("if (!cq5forms_isEmpty("); out.write(qualifier); out.write(")){"); try { request.setAttribute(ATTR_DESC, desc);
final Resource includeResource = new ResourceWrapper(desc.getFieldResource(),
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FieldHelper.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/FormsHandlingResponse.java // public class FormsHandlingResponse extends SlingHttpServletResponseWrapper { // // private ServletOutputStream nullstream; // private PrintWriter nullwriter; // // public FormsHandlingResponse(SlingHttpServletResponse wrappedResponse) { // super(wrappedResponse); // } // // @Override // public PrintWriter getWriter() { // if (nullwriter == null) { // nullwriter = new PrintWriter(getOutputStream()); // } // return nullwriter; // } // // @Override // public ServletOutputStream getOutputStream() { // if (nullstream == null) { // nullstream = new ServletOutputStream() { // // @Override // public void write(int b) { // // noop // } // // @Override // public void write(byte[] b) { // // noop // } // // @Override // public void write(byte[] b, int off, int len) // { // // noop // } // // @Override // public void flush() { // // noop // } // // @Override // public void close() { // // noop // } // }; // } // return nullstream; // } // // @Override // public void flushBuffer() { // // noop // } // // @Override // public void reset() { // // noop // } // // @Override // public void resetBuffer() { // // noop // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.FormsHandlingResponse; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper;
if ( desc.isRequired() && isEmpty(request, desc.getName()) && doValidation(request, desc) ) { ValidationInfo.createValidationInfo(request).addErrorMessage(desc.getName(), desc.getRequiredMessage()); return false; } return true; } /** * Determine if the field has to be validated. If no or a single post resources * is defined the field is always validated. Multiple post resources are only * validated when the @Write parameter is set. * is set */ private static boolean doValidation(SlingHttpServletRequest request, FieldDescription desc) { return request.getParameter(desc.getName() + FormResourceEdit.WRITE_SUFFIX) != null || FormResourceEdit.isSingleResourcePost(request); } /** * Private method to initialize the field. */ private static void initField(final SlingHttpServletRequest req, final SlingHttpServletResponse res, final Resource rsrc) throws ServletException, IOException { final String key = getInitAttrName(rsrc); final Object flag = req.getAttribute(key); if ( flag == null ) { req.setAttribute(key, Boolean.TRUE);
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/FormsHandlingResponse.java // public class FormsHandlingResponse extends SlingHttpServletResponseWrapper { // // private ServletOutputStream nullstream; // private PrintWriter nullwriter; // // public FormsHandlingResponse(SlingHttpServletResponse wrappedResponse) { // super(wrappedResponse); // } // // @Override // public PrintWriter getWriter() { // if (nullwriter == null) { // nullwriter = new PrintWriter(getOutputStream()); // } // return nullwriter; // } // // @Override // public ServletOutputStream getOutputStream() { // if (nullstream == null) { // nullstream = new ServletOutputStream() { // // @Override // public void write(int b) { // // noop // } // // @Override // public void write(byte[] b) { // // noop // } // // @Override // public void write(byte[] b, int off, int len) // { // // noop // } // // @Override // public void flush() { // // noop // } // // @Override // public void close() { // // noop // } // }; // } // return nullstream; // } // // @Override // public void flushBuffer() { // // noop // } // // @Override // public void reset() { // // noop // } // // @Override // public void resetBuffer() { // // noop // } // } // // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/impl/ResourceWrapper.java // public class ResourceWrapper extends org.apache.sling.api.resource.ResourceWrapper { // // private final String resourceType; // // private final String resourceSuperType; // // public ResourceWrapper(final Resource r, final String rt, final String rst) { // super(r); // this.resourceType = rt; // this.resourceSuperType = rst; // } // // public String getResourceSuperType() { // return this.resourceSuperType; // } // // public String getResourceType() { // return this.resourceType; // } // } // Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/forms/FieldHelper.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ValueMap; import com.day.cq.wcm.foundation.forms.impl.FormsHandlingResponse; import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper; if ( desc.isRequired() && isEmpty(request, desc.getName()) && doValidation(request, desc) ) { ValidationInfo.createValidationInfo(request).addErrorMessage(desc.getName(), desc.getRequiredMessage()); return false; } return true; } /** * Determine if the field has to be validated. If no or a single post resources * is defined the field is always validated. Multiple post resources are only * validated when the @Write parameter is set. * is set */ private static boolean doValidation(SlingHttpServletRequest request, FieldDescription desc) { return request.getParameter(desc.getName() + FormResourceEdit.WRITE_SUFFIX) != null || FormResourceEdit.isSingleResourcePost(request); } /** * Private method to initialize the field. */ private static void initField(final SlingHttpServletRequest req, final SlingHttpServletResponse res, final Resource rsrc) throws ServletException, IOException { final String key = getInitAttrName(rsrc); final Object flag = req.getAttribute(key); if ( flag == null ) { req.setAttribute(key, Boolean.TRUE);
FormsHelper.includeResource(req, new FormsHandlingResponse(res), rsrc, FormsConstants.SCRIPT_FIELD_INIT);
ooyala/Ooyala-AdobeCQ
ui/src/content/jcr_root/libs/foundation/components/title/title.png.java
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/ImageHelper.java // public class ImageHelper extends com.day.cq.commons.ImageHelper { // }
import java.awt.Color; import java.awt.geom.Rectangle2D; import java.io.IOException; import javax.jcr.RepositoryException; import com.day.cq.commons.jcr.JcrConstants; import com.day.cq.wcm.api.designer.Style; import com.day.cq.wcm.commons.AbstractImageServlet; import com.day.cq.wcm.foundation.ImageHelper; import com.day.image.Font; import com.day.image.Layer; import org.apache.sling.api.resource.Resource;
/* * Copyright 1997-2008 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package libs.foundation.components.title; /** * Title image servlet */ public class title_png extends AbstractImageServlet { protected Layer createLayer(ImageContext c) throws RepositoryException, IOException { // read the style information (we don't use css names). Style style = c.style.getSubStyle("titleimage"); String fontFace = style.get("fontFamily", "Myriad Pro"); long fontSize = style.get("fontSize", 10L);
// Path: ui/src/content/jcr_root/libs/foundation/src/impl/src/main/java/com/day/cq/wcm/foundation/ImageHelper.java // public class ImageHelper extends com.day.cq.commons.ImageHelper { // } // Path: ui/src/content/jcr_root/libs/foundation/components/title/title.png.java import java.awt.Color; import java.awt.geom.Rectangle2D; import java.io.IOException; import javax.jcr.RepositoryException; import com.day.cq.commons.jcr.JcrConstants; import com.day.cq.wcm.api.designer.Style; import com.day.cq.wcm.commons.AbstractImageServlet; import com.day.cq.wcm.foundation.ImageHelper; import com.day.image.Font; import com.day.image.Layer; import org.apache.sling.api.resource.Resource; /* * Copyright 1997-2008 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package libs.foundation.components.title; /** * Title image servlet */ public class title_png extends AbstractImageServlet { protected Layer createLayer(ImageContext c) throws RepositoryException, IOException { // read the style information (we don't use css names). Style style = c.style.getSubStyle("titleimage"); String fontFace = style.get("fontFamily", "Myriad Pro"); long fontSize = style.get("fontSize", 10L);
int fontStyle = ImageHelper.parseFontStyle(style.get("fontStyle", "bold"));
dotcool/coolreader
src/com/dotcool/reader/fragment/DisplayNovelTabFragment.java
// Path: src/com/dotcool/reader/activity/INovelListHelper.java // public interface INovelListHelper { // public void manualAdd(); // public void downloadAllNovelInfo(); // public void refreshList(); // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTabHost; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.dotcool.R; import com.dotcool.reader.activity.INovelListHelper;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_display_novel_tab, container, false); mTabHost = (FragmentTabHost) view.findViewById(android.R.id.tabhost); mTabHost.setup(getSherlockActivity(), getChildFragmentManager(), R.id.content); mTabHost.addTab(mTabHost.newTabSpec(MAIN_SPEC).setIndicator(MAIN_SPEC), DisplayLightNovelListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec(TEASER_SPEC).setIndicator(TEASER_SPEC), DisplayTeaserListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec(ORIGINAL_SPEC).setIndicator(ORIGINAL_SPEC), DisplayOriginalListFragment.class, null); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // set menu for main/teaser/original inflater.inflate(R.menu.fragment_display_novel_tab, menu); } @Override public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) { Fragment currentTab = getChildFragmentManager().findFragmentById(R.id.content); Log.d(TAG, "Current fragment: " + currentTab.getClass().toString()); switch(item.getItemId()) { case R.id.menu_manual_add:
// Path: src/com/dotcool/reader/activity/INovelListHelper.java // public interface INovelListHelper { // public void manualAdd(); // public void downloadAllNovelInfo(); // public void refreshList(); // // } // Path: src/com/dotcool/reader/fragment/DisplayNovelTabFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTabHost; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.dotcool.R; import com.dotcool.reader.activity.INovelListHelper; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_display_novel_tab, container, false); mTabHost = (FragmentTabHost) view.findViewById(android.R.id.tabhost); mTabHost.setup(getSherlockActivity(), getChildFragmentManager(), R.id.content); mTabHost.addTab(mTabHost.newTabSpec(MAIN_SPEC).setIndicator(MAIN_SPEC), DisplayLightNovelListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec(TEASER_SPEC).setIndicator(TEASER_SPEC), DisplayTeaserListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec(ORIGINAL_SPEC).setIndicator(ORIGINAL_SPEC), DisplayOriginalListFragment.class, null); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // set menu for main/teaser/original inflater.inflate(R.menu.fragment_display_novel_tab, menu); } @Override public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) { Fragment currentTab = getChildFragmentManager().findFragmentById(R.id.content); Log.d(TAG, "Current fragment: " + currentTab.getClass().toString()); switch(item.getItemId()) { case R.id.menu_manual_add:
if(currentTab instanceof INovelListHelper)
dotcool/coolreader
src/com/dotcool/view/AboutActivity.java
// Path: src/com/nil/lu/ads/L.java // public class L // { // public static int JIFEN_MAX = 100; // public static int JIFEN_MAX_END = 200; // public static int SHOW_TIMES = 0; // // public static int getCount(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // } // // public static int getJifen(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("jifen", 0); // } // // public static boolean getJifenCountAccess(Context paramContext) // { // SharedPreferences localSharedPreferences = paramContext.getSharedPreferences("ads", 0); // int i = localSharedPreferences.getInt("jifen", 0); // if (localSharedPreferences.getInt("count", 0) <= SHOW_TIMES){ // return false; // }else if ((i >= JIFEN_MAX_END) || (i >= JIFEN_MAX)){ // return false; // } // return true; // } // // public static boolean getShowAds(Context paramContext) // { // int i = paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // int j = SHOW_TIMES; // boolean bool = false; // if (i >= j) // bool = true; // return bool; // } // // public static void setPlayCount(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("count", paramInt); // localEditor.commit(); // } // // public static void setYoumiJifen(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("jifen", paramInt); // localEditor.commit(); // } // } // // Path: src/com/nil/lu/ads/MainAdsActivity.java // public class MainAdsActivity extends Activity // implements PointsChangeNotify, View.OnClickListener // { // private TextView mTextViewPointsBalance; // // private void initViews() // { // findViewById(2131165185).setOnClickListener(this); // this.mTextViewPointsBalance = ((TextView)findViewById(2131165184)); // this.mTextViewPointsBalance.setText("经验值:" + PointsManager.getInstance(this).queryPoints()); // L.setYoumiJifen(this, PointsManager.getInstance(this).queryPoints()); // } // // public void onClick(View paramView) // { // switch (paramView.getId()) // { // default: // return; // case 2131165185: // } // OffersManager.getInstance(this).showOffersWall(); // } // // protected void onCreate(Bundle paramBundle) // { // super.onCreate(paramBundle); // setContentView(2130903040); // initViews(); // AdManager.getInstance(this).init("0b72edb291dc1783", "96198b6864575a0d", false); // OffersManager.getInstance(this).onAppLaunch(); // PointsManager.getInstance(this).registerNotify(this); // new UpdateHelper(this).execute(new Void[0]); // } // // protected void onDestroy() // { // super.onDestroy(); // OffersManager.getInstance(this).onAppExit(); // PointsManager.getInstance(this).unRegisterNotify(this); // } // // public void onPointBalanceChange(int paramInt) // { // this.mTextViewPointsBalance.setText("经验值:" + paramInt); // L.setYoumiJifen(this, paramInt); // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.app.SherlockListActivity; import com.dotcool.R; import com.nil.lu.ads.L; import com.nil.lu.ads.MainAdsActivity;
}); SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.about_list_item, new String[]{"title"}, new int[]{R.id.about_list_item_text}){ @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); final TextView rl = (TextView)view.findViewById(R.id.about_list_item_text); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if(rl.getText()=="积分"){ Ad(); }else if(rl.getText()=="关于"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书", 0).show(); }else if(rl.getText()=="分享设置"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); }else if(rl.getText()=="登陆"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); } } }); return view; } }; aboutListV.setAdapter(adapter); } private void Ad(){
// Path: src/com/nil/lu/ads/L.java // public class L // { // public static int JIFEN_MAX = 100; // public static int JIFEN_MAX_END = 200; // public static int SHOW_TIMES = 0; // // public static int getCount(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // } // // public static int getJifen(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("jifen", 0); // } // // public static boolean getJifenCountAccess(Context paramContext) // { // SharedPreferences localSharedPreferences = paramContext.getSharedPreferences("ads", 0); // int i = localSharedPreferences.getInt("jifen", 0); // if (localSharedPreferences.getInt("count", 0) <= SHOW_TIMES){ // return false; // }else if ((i >= JIFEN_MAX_END) || (i >= JIFEN_MAX)){ // return false; // } // return true; // } // // public static boolean getShowAds(Context paramContext) // { // int i = paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // int j = SHOW_TIMES; // boolean bool = false; // if (i >= j) // bool = true; // return bool; // } // // public static void setPlayCount(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("count", paramInt); // localEditor.commit(); // } // // public static void setYoumiJifen(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("jifen", paramInt); // localEditor.commit(); // } // } // // Path: src/com/nil/lu/ads/MainAdsActivity.java // public class MainAdsActivity extends Activity // implements PointsChangeNotify, View.OnClickListener // { // private TextView mTextViewPointsBalance; // // private void initViews() // { // findViewById(2131165185).setOnClickListener(this); // this.mTextViewPointsBalance = ((TextView)findViewById(2131165184)); // this.mTextViewPointsBalance.setText("经验值:" + PointsManager.getInstance(this).queryPoints()); // L.setYoumiJifen(this, PointsManager.getInstance(this).queryPoints()); // } // // public void onClick(View paramView) // { // switch (paramView.getId()) // { // default: // return; // case 2131165185: // } // OffersManager.getInstance(this).showOffersWall(); // } // // protected void onCreate(Bundle paramBundle) // { // super.onCreate(paramBundle); // setContentView(2130903040); // initViews(); // AdManager.getInstance(this).init("0b72edb291dc1783", "96198b6864575a0d", false); // OffersManager.getInstance(this).onAppLaunch(); // PointsManager.getInstance(this).registerNotify(this); // new UpdateHelper(this).execute(new Void[0]); // } // // protected void onDestroy() // { // super.onDestroy(); // OffersManager.getInstance(this).onAppExit(); // PointsManager.getInstance(this).unRegisterNotify(this); // } // // public void onPointBalanceChange(int paramInt) // { // this.mTextViewPointsBalance.setText("经验值:" + paramInt); // L.setYoumiJifen(this, paramInt); // } // } // Path: src/com/dotcool/view/AboutActivity.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.app.SherlockListActivity; import com.dotcool.R; import com.nil.lu.ads.L; import com.nil.lu.ads.MainAdsActivity; }); SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.about_list_item, new String[]{"title"}, new int[]{R.id.about_list_item_text}){ @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); final TextView rl = (TextView)view.findViewById(R.id.about_list_item_text); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if(rl.getText()=="积分"){ Ad(); }else if(rl.getText()=="关于"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书", 0).show(); }else if(rl.getText()=="分享设置"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); }else if(rl.getText()=="登陆"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); } } }); return view; } }; aboutListV.setAdapter(adapter); } private void Ad(){
if (L.getJifenCountAccess(AboutActivity.this)==false){
dotcool/coolreader
src/com/dotcool/view/AboutActivity.java
// Path: src/com/nil/lu/ads/L.java // public class L // { // public static int JIFEN_MAX = 100; // public static int JIFEN_MAX_END = 200; // public static int SHOW_TIMES = 0; // // public static int getCount(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // } // // public static int getJifen(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("jifen", 0); // } // // public static boolean getJifenCountAccess(Context paramContext) // { // SharedPreferences localSharedPreferences = paramContext.getSharedPreferences("ads", 0); // int i = localSharedPreferences.getInt("jifen", 0); // if (localSharedPreferences.getInt("count", 0) <= SHOW_TIMES){ // return false; // }else if ((i >= JIFEN_MAX_END) || (i >= JIFEN_MAX)){ // return false; // } // return true; // } // // public static boolean getShowAds(Context paramContext) // { // int i = paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // int j = SHOW_TIMES; // boolean bool = false; // if (i >= j) // bool = true; // return bool; // } // // public static void setPlayCount(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("count", paramInt); // localEditor.commit(); // } // // public static void setYoumiJifen(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("jifen", paramInt); // localEditor.commit(); // } // } // // Path: src/com/nil/lu/ads/MainAdsActivity.java // public class MainAdsActivity extends Activity // implements PointsChangeNotify, View.OnClickListener // { // private TextView mTextViewPointsBalance; // // private void initViews() // { // findViewById(2131165185).setOnClickListener(this); // this.mTextViewPointsBalance = ((TextView)findViewById(2131165184)); // this.mTextViewPointsBalance.setText("经验值:" + PointsManager.getInstance(this).queryPoints()); // L.setYoumiJifen(this, PointsManager.getInstance(this).queryPoints()); // } // // public void onClick(View paramView) // { // switch (paramView.getId()) // { // default: // return; // case 2131165185: // } // OffersManager.getInstance(this).showOffersWall(); // } // // protected void onCreate(Bundle paramBundle) // { // super.onCreate(paramBundle); // setContentView(2130903040); // initViews(); // AdManager.getInstance(this).init("0b72edb291dc1783", "96198b6864575a0d", false); // OffersManager.getInstance(this).onAppLaunch(); // PointsManager.getInstance(this).registerNotify(this); // new UpdateHelper(this).execute(new Void[0]); // } // // protected void onDestroy() // { // super.onDestroy(); // OffersManager.getInstance(this).onAppExit(); // PointsManager.getInstance(this).unRegisterNotify(this); // } // // public void onPointBalanceChange(int paramInt) // { // this.mTextViewPointsBalance.setText("经验值:" + paramInt); // L.setYoumiJifen(this, paramInt); // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.app.SherlockListActivity; import com.dotcool.R; import com.nil.lu.ads.L; import com.nil.lu.ads.MainAdsActivity;
new String[]{"title"}, new int[]{R.id.about_list_item_text}){ @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); final TextView rl = (TextView)view.findViewById(R.id.about_list_item_text); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if(rl.getText()=="积分"){ Ad(); }else if(rl.getText()=="关于"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书", 0).show(); }else if(rl.getText()=="分享设置"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); }else if(rl.getText()=="登陆"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); } } }); return view; } }; aboutListV.setAdapter(adapter); } private void Ad(){ if (L.getJifenCountAccess(AboutActivity.this)==false){ Log.d("dots","false"); Toast.makeText(AboutActivity.this, "请先获取经验大于0", 0).show();
// Path: src/com/nil/lu/ads/L.java // public class L // { // public static int JIFEN_MAX = 100; // public static int JIFEN_MAX_END = 200; // public static int SHOW_TIMES = 0; // // public static int getCount(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // } // // public static int getJifen(Context paramContext) // { // return paramContext.getSharedPreferences("ads", 0).getInt("jifen", 0); // } // // public static boolean getJifenCountAccess(Context paramContext) // { // SharedPreferences localSharedPreferences = paramContext.getSharedPreferences("ads", 0); // int i = localSharedPreferences.getInt("jifen", 0); // if (localSharedPreferences.getInt("count", 0) <= SHOW_TIMES){ // return false; // }else if ((i >= JIFEN_MAX_END) || (i >= JIFEN_MAX)){ // return false; // } // return true; // } // // public static boolean getShowAds(Context paramContext) // { // int i = paramContext.getSharedPreferences("ads", 0).getInt("count", 0); // int j = SHOW_TIMES; // boolean bool = false; // if (i >= j) // bool = true; // return bool; // } // // public static void setPlayCount(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("count", paramInt); // localEditor.commit(); // } // // public static void setYoumiJifen(Context paramContext, int paramInt) // { // SharedPreferences.Editor localEditor = paramContext.getSharedPreferences("ads", 0).edit(); // localEditor.putInt("jifen", paramInt); // localEditor.commit(); // } // } // // Path: src/com/nil/lu/ads/MainAdsActivity.java // public class MainAdsActivity extends Activity // implements PointsChangeNotify, View.OnClickListener // { // private TextView mTextViewPointsBalance; // // private void initViews() // { // findViewById(2131165185).setOnClickListener(this); // this.mTextViewPointsBalance = ((TextView)findViewById(2131165184)); // this.mTextViewPointsBalance.setText("经验值:" + PointsManager.getInstance(this).queryPoints()); // L.setYoumiJifen(this, PointsManager.getInstance(this).queryPoints()); // } // // public void onClick(View paramView) // { // switch (paramView.getId()) // { // default: // return; // case 2131165185: // } // OffersManager.getInstance(this).showOffersWall(); // } // // protected void onCreate(Bundle paramBundle) // { // super.onCreate(paramBundle); // setContentView(2130903040); // initViews(); // AdManager.getInstance(this).init("0b72edb291dc1783", "96198b6864575a0d", false); // OffersManager.getInstance(this).onAppLaunch(); // PointsManager.getInstance(this).registerNotify(this); // new UpdateHelper(this).execute(new Void[0]); // } // // protected void onDestroy() // { // super.onDestroy(); // OffersManager.getInstance(this).onAppExit(); // PointsManager.getInstance(this).unRegisterNotify(this); // } // // public void onPointBalanceChange(int paramInt) // { // this.mTextViewPointsBalance.setText("经验值:" + paramInt); // L.setYoumiJifen(this, paramInt); // } // } // Path: src/com/dotcool/view/AboutActivity.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.app.SherlockListActivity; import com.dotcool.R; import com.nil.lu.ads.L; import com.nil.lu.ads.MainAdsActivity; new String[]{"title"}, new int[]{R.id.about_list_item_text}){ @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); final TextView rl = (TextView)view.findViewById(R.id.about_list_item_text); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if(rl.getText()=="积分"){ Ad(); }else if(rl.getText()=="关于"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书", 0).show(); }else if(rl.getText()=="分享设置"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); }else if(rl.getText()=="登陆"){ Toast.makeText(AboutActivity.this, "感谢使用,点酷听书,暂未开放", 0).show(); } } }); return view; } }; aboutListV.setAdapter(adapter); } private void Ad(){ if (L.getJifenCountAccess(AboutActivity.this)==false){ Log.d("dots","false"); Toast.makeText(AboutActivity.this, "请先获取经验大于0", 0).show();
Intent localIntent1 = new Intent(AboutActivity.this, MainAdsActivity.class);
dotcool/coolreader
src/com/dotcool/reader/task/IAsyncTaskOwner.java
// Path: src/com/dotcool/reader/callback/ICallbackEventData.java // public interface ICallbackEventData { // // public abstract String getMessage(); // public abstract void setMessage(String message); // } // // Path: src/com/dotcool/reader/helper/AsyncTaskResult.java // public class AsyncTaskResult<T> { // private T result; // private Exception error; // // // public T getResult() { // return result; // } // public Exception getError() { // return error; // } // // // public AsyncTaskResult(T result) { // super(); // this.result = result; // } // // // public AsyncTaskResult(Exception error) { // super(); // this.error = error; // } // // }
import android.content.Context; import com.dotcool.reader.callback.ICallbackEventData; import com.dotcool.reader.helper.AsyncTaskResult;
package com.dotcool.reader.task; public interface IAsyncTaskOwner { void updateProgress(String id, int current, int total, String message); boolean downloadListSetup(String id, String toastText, int type, boolean hasError); void toggleProgressBar(boolean show);
// Path: src/com/dotcool/reader/callback/ICallbackEventData.java // public interface ICallbackEventData { // // public abstract String getMessage(); // public abstract void setMessage(String message); // } // // Path: src/com/dotcool/reader/helper/AsyncTaskResult.java // public class AsyncTaskResult<T> { // private T result; // private Exception error; // // // public T getResult() { // return result; // } // public Exception getError() { // return error; // } // // // public AsyncTaskResult(T result) { // super(); // this.result = result; // } // // // public AsyncTaskResult(Exception error) { // super(); // this.error = error; // } // // } // Path: src/com/dotcool/reader/task/IAsyncTaskOwner.java import android.content.Context; import com.dotcool.reader.callback.ICallbackEventData; import com.dotcool.reader.helper.AsyncTaskResult; package com.dotcool.reader.task; public interface IAsyncTaskOwner { void updateProgress(String id, int current, int total, String message); boolean downloadListSetup(String id, String toastText, int type, boolean hasError); void toggleProgressBar(boolean show);
void setMessageDialog(ICallbackEventData message);
dotcool/coolreader
src/com/dotcool/reader/task/IAsyncTaskOwner.java
// Path: src/com/dotcool/reader/callback/ICallbackEventData.java // public interface ICallbackEventData { // // public abstract String getMessage(); // public abstract void setMessage(String message); // } // // Path: src/com/dotcool/reader/helper/AsyncTaskResult.java // public class AsyncTaskResult<T> { // private T result; // private Exception error; // // // public T getResult() { // return result; // } // public Exception getError() { // return error; // } // // // public AsyncTaskResult(T result) { // super(); // this.result = result; // } // // // public AsyncTaskResult(Exception error) { // super(); // this.error = error; // } // // }
import android.content.Context; import com.dotcool.reader.callback.ICallbackEventData; import com.dotcool.reader.helper.AsyncTaskResult;
package com.dotcool.reader.task; public interface IAsyncTaskOwner { void updateProgress(String id, int current, int total, String message); boolean downloadListSetup(String id, String toastText, int type, boolean hasError); void toggleProgressBar(boolean show); void setMessageDialog(ICallbackEventData message);
// Path: src/com/dotcool/reader/callback/ICallbackEventData.java // public interface ICallbackEventData { // // public abstract String getMessage(); // public abstract void setMessage(String message); // } // // Path: src/com/dotcool/reader/helper/AsyncTaskResult.java // public class AsyncTaskResult<T> { // private T result; // private Exception error; // // // public T getResult() { // return result; // } // public Exception getError() { // return error; // } // // // public AsyncTaskResult(T result) { // super(); // this.result = result; // } // // // public AsyncTaskResult(Exception error) { // super(); // this.error = error; // } // // } // Path: src/com/dotcool/reader/task/IAsyncTaskOwner.java import android.content.Context; import com.dotcool.reader.callback.ICallbackEventData; import com.dotcool.reader.helper.AsyncTaskResult; package com.dotcool.reader.task; public interface IAsyncTaskOwner { void updateProgress(String id, int current, int total, String message); boolean downloadListSetup(String id, String toastText, int type, boolean hasError); void toggleProgressBar(boolean show); void setMessageDialog(ICallbackEventData message);
void onGetResult(AsyncTaskResult<?> result, Class<?> type);
dotcool/coolreader
src/com/dotcool/bll/Dao.java
// Path: src/com/dotcool/dal/BookDownloadHelper.java // public class BookDownloadHelper extends SQLiteOpenHelper { // // download.db-->数据库名 // public BookDownloadHelper(Context context) { // super(context, "download.db", null, 1); // } // // /** // * 在download.db数据库下创建一个download_info表存储下载信息 // */ // @Override // public void onCreate(SQLiteDatabase db) { // db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, " // + "start_pos integer, end_pos integer, compelete_size integer,url char)"); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // // } // // } // // Path: src/com/dotcool/model/DownloadInfo.java // public class DownloadInfo { // // private int threadId;// 下载器id // private int startPos;// 开始点 // private int endPos;// 结束点 // private int compeleteSize;// 完成度 // private String url;// 下载器网络标识 // // // // public DownloadInfo(int threadId, int startPos, int endPos, // int compeleteSize, String url) { // super(); // this.threadId = threadId; // this.startPos = startPos; // this.endPos = endPos; // this.compeleteSize = compeleteSize; // this.url = url; // } // public int getThreadId() { // return threadId; // } // public void setThreadId(int threadId) { // this.threadId = threadId; // } // public int getStartPos() { // return startPos; // } // public void setStartPos(int startPos) { // this.startPos = startPos; // } // public int getEndPos() { // return endPos; // } // public void setEndPos(int endPos) { // this.endPos = endPos; // } // public int getCompeleteSize() { // return compeleteSize; // } // public void setCompeleteSize(int compeleteSize) { // this.compeleteSize = compeleteSize; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // // @Override // public String toString() { // return "DownloadInfo [threadId=" + threadId // + ", startPos=" + startPos + ", endPos=" + endPos // + ", compeleteSize=" + compeleteSize +"]"; // } // // // }
import java.util.ArrayList; import java.util.List; import com.dotcool.dal.BookDownloadHelper; import com.dotcool.model.DownloadInfo; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
package com.dotcool.bll; /** * * 一个业务类 */ public class Dao { private BookDownloadHelper dbHelper; public Dao(Context context) { dbHelper = new BookDownloadHelper(context); } /** * 查看数据库中是否有数据 */ public boolean isHasInfors(String urlstr) { SQLiteDatabase database = dbHelper.getReadableDatabase(); String sql = "select count(*) from download_info where url=?"; Cursor cursor = database.rawQuery(sql, new String[] { urlstr }); cursor.moveToFirst(); int count = cursor.getInt(0); cursor.close(); return count == 0; } /** * 保存 下载的具体信息 */
// Path: src/com/dotcool/dal/BookDownloadHelper.java // public class BookDownloadHelper extends SQLiteOpenHelper { // // download.db-->数据库名 // public BookDownloadHelper(Context context) { // super(context, "download.db", null, 1); // } // // /** // * 在download.db数据库下创建一个download_info表存储下载信息 // */ // @Override // public void onCreate(SQLiteDatabase db) { // db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, " // + "start_pos integer, end_pos integer, compelete_size integer,url char)"); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // // } // // } // // Path: src/com/dotcool/model/DownloadInfo.java // public class DownloadInfo { // // private int threadId;// 下载器id // private int startPos;// 开始点 // private int endPos;// 结束点 // private int compeleteSize;// 完成度 // private String url;// 下载器网络标识 // // // // public DownloadInfo(int threadId, int startPos, int endPos, // int compeleteSize, String url) { // super(); // this.threadId = threadId; // this.startPos = startPos; // this.endPos = endPos; // this.compeleteSize = compeleteSize; // this.url = url; // } // public int getThreadId() { // return threadId; // } // public void setThreadId(int threadId) { // this.threadId = threadId; // } // public int getStartPos() { // return startPos; // } // public void setStartPos(int startPos) { // this.startPos = startPos; // } // public int getEndPos() { // return endPos; // } // public void setEndPos(int endPos) { // this.endPos = endPos; // } // public int getCompeleteSize() { // return compeleteSize; // } // public void setCompeleteSize(int compeleteSize) { // this.compeleteSize = compeleteSize; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // // @Override // public String toString() { // return "DownloadInfo [threadId=" + threadId // + ", startPos=" + startPos + ", endPos=" + endPos // + ", compeleteSize=" + compeleteSize +"]"; // } // // // } // Path: src/com/dotcool/bll/Dao.java import java.util.ArrayList; import java.util.List; import com.dotcool.dal.BookDownloadHelper; import com.dotcool.model.DownloadInfo; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; package com.dotcool.bll; /** * * 一个业务类 */ public class Dao { private BookDownloadHelper dbHelper; public Dao(Context context) { dbHelper = new BookDownloadHelper(context); } /** * 查看数据库中是否有数据 */ public boolean isHasInfors(String urlstr) { SQLiteDatabase database = dbHelper.getReadableDatabase(); String sql = "select count(*) from download_info where url=?"; Cursor cursor = database.rawQuery(sql, new String[] { urlstr }); cursor.moveToFirst(); int count = cursor.getInt(0); cursor.close(); return count == 0; } /** * 保存 下载的具体信息 */
public void saveInfos(List<DownloadInfo> infos) {
apiman/apiman-plugins
jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/JsonpPolicy.java
// Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/beans/JsonpConfigBean.java // public class JsonpConfigBean { // // @JsonProperty // private String callbackParamName; // // /** // * @return the parameter name used to specify the callback function // */ // public String getCallbackParamName() { // return callbackParamName; // } // // /** // * @param callbackParamName the parameter name used to specify the callback function // */ // public void setCallbackParamName(String callbackParamName) { // this.callbackParamName = callbackParamName; // } // } // // Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/http/HttpHeaders.java // public class HttpHeaders { // // private static final String CONTENT_TYPE = "Content-Type"; //$NON-NLS-1$ // private static final String CONTENT_LENGTH = "Content-Length"; //$NON-NLS-1$ // // private final HeaderMap headers; // // /** // * Constructor. // * // * @param headers headers map // */ // public HttpHeaders(HeaderMap headers) { // this.headers = headers; // } // // /** // * Extract the charset from the Content-Type header. When not present, the default charset is returned. // * // * @param defaultCharset the default charset // * @return charset // */ // public String getCharsetFromContentType(String defaultCharset) { // String charset = null; // String contentTypeStr = headers.get(CONTENT_TYPE); // if (contentTypeStr != null) { // charset = new ContentType(contentTypeStr).getCharset(); // } // return charset != null ? charset : defaultCharset; // } // // /** // * Set the type/subtype value of the Content-Type header. // * // * @param typeSubtype the type/subtype value // */ // public void setContentType(String typeSubtype) { // String contentTypeStr = headers.get(CONTENT_TYPE); // if (contentTypeStr != null) { // ContentType contentType = new ContentType(contentTypeStr); // contentType.setTypeSubtype(typeSubtype); // headers.put(CONTENT_TYPE, contentType.toString()); // } else { // headers.put(CONTENT_TYPE, typeSubtype); // } // } // // /** // * @param additionalContentLength the additional content length // */ // public void incrementContentLength(int additionalContentLength) { // String cl = headers.get(CONTENT_LENGTH); // if (cl != null && cl.length() > 0) { // int clength = new Integer(cl).intValue(); // headers.put(CONTENT_LENGTH, String.valueOf(clength + additionalContentLength)); // } // } // // }
import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.gateway.engine.components.IBufferFactoryComponent; import io.apiman.gateway.engine.io.AbstractStream; import io.apiman.gateway.engine.io.IApimanBuffer; import io.apiman.gateway.engine.io.IReadWriteStream; import io.apiman.gateway.engine.policies.AbstractMappedPolicy; import io.apiman.gateway.engine.policy.IDataPolicy; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.plugins.jsonp_policy.beans.JsonpConfigBean; import io.apiman.plugins.jsonp_policy.http.HttpHeaders; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets;
@Override protected void doApply(ApiRequest request, IPolicyContext context, JsonpConfigBean config, IPolicyChain<ApiRequest> chain) { String callbackParamName = config.getCallbackParamName(); String callbackFunctionName = request.getQueryParams().get(callbackParamName); request.getQueryParams().remove(callbackParamName); if (callbackFunctionName != null) { context.setAttribute(CALLBACK_FUNCTION_NAME, callbackFunctionName); } super.doApply(request, context, config, chain); } /** * @see io.apiman.gateway.engine.policy.IDataPolicy#getRequestDataHandler(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object) */ @Override public IReadWriteStream<ApiRequest> getRequestDataHandler(ApiRequest request, IPolicyContext context, Object policyConfiguration) { return null; } /** * @see io.apiman.gateway.engine.policy.IDataPolicy#getResponseDataHandler(io.apiman.gateway.engine.beans.ApiResponse, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object) */ @Override public IReadWriteStream<ApiResponse> getResponseDataHandler(final ApiResponse response, IPolicyContext context, Object policyConfiguration) { final String callbackFunctionName = (String) context.getAttribute(CALLBACK_FUNCTION_NAME, null); if (callbackFunctionName != null) {
// Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/beans/JsonpConfigBean.java // public class JsonpConfigBean { // // @JsonProperty // private String callbackParamName; // // /** // * @return the parameter name used to specify the callback function // */ // public String getCallbackParamName() { // return callbackParamName; // } // // /** // * @param callbackParamName the parameter name used to specify the callback function // */ // public void setCallbackParamName(String callbackParamName) { // this.callbackParamName = callbackParamName; // } // } // // Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/http/HttpHeaders.java // public class HttpHeaders { // // private static final String CONTENT_TYPE = "Content-Type"; //$NON-NLS-1$ // private static final String CONTENT_LENGTH = "Content-Length"; //$NON-NLS-1$ // // private final HeaderMap headers; // // /** // * Constructor. // * // * @param headers headers map // */ // public HttpHeaders(HeaderMap headers) { // this.headers = headers; // } // // /** // * Extract the charset from the Content-Type header. When not present, the default charset is returned. // * // * @param defaultCharset the default charset // * @return charset // */ // public String getCharsetFromContentType(String defaultCharset) { // String charset = null; // String contentTypeStr = headers.get(CONTENT_TYPE); // if (contentTypeStr != null) { // charset = new ContentType(contentTypeStr).getCharset(); // } // return charset != null ? charset : defaultCharset; // } // // /** // * Set the type/subtype value of the Content-Type header. // * // * @param typeSubtype the type/subtype value // */ // public void setContentType(String typeSubtype) { // String contentTypeStr = headers.get(CONTENT_TYPE); // if (contentTypeStr != null) { // ContentType contentType = new ContentType(contentTypeStr); // contentType.setTypeSubtype(typeSubtype); // headers.put(CONTENT_TYPE, contentType.toString()); // } else { // headers.put(CONTENT_TYPE, typeSubtype); // } // } // // /** // * @param additionalContentLength the additional content length // */ // public void incrementContentLength(int additionalContentLength) { // String cl = headers.get(CONTENT_LENGTH); // if (cl != null && cl.length() > 0) { // int clength = new Integer(cl).intValue(); // headers.put(CONTENT_LENGTH, String.valueOf(clength + additionalContentLength)); // } // } // // } // Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/JsonpPolicy.java import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.gateway.engine.components.IBufferFactoryComponent; import io.apiman.gateway.engine.io.AbstractStream; import io.apiman.gateway.engine.io.IApimanBuffer; import io.apiman.gateway.engine.io.IReadWriteStream; import io.apiman.gateway.engine.policies.AbstractMappedPolicy; import io.apiman.gateway.engine.policy.IDataPolicy; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.plugins.jsonp_policy.beans.JsonpConfigBean; import io.apiman.plugins.jsonp_policy.http.HttpHeaders; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; @Override protected void doApply(ApiRequest request, IPolicyContext context, JsonpConfigBean config, IPolicyChain<ApiRequest> chain) { String callbackParamName = config.getCallbackParamName(); String callbackFunctionName = request.getQueryParams().get(callbackParamName); request.getQueryParams().remove(callbackParamName); if (callbackFunctionName != null) { context.setAttribute(CALLBACK_FUNCTION_NAME, callbackFunctionName); } super.doApply(request, context, config, chain); } /** * @see io.apiman.gateway.engine.policy.IDataPolicy#getRequestDataHandler(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object) */ @Override public IReadWriteStream<ApiRequest> getRequestDataHandler(ApiRequest request, IPolicyContext context, Object policyConfiguration) { return null; } /** * @see io.apiman.gateway.engine.policy.IDataPolicy#getResponseDataHandler(io.apiman.gateway.engine.beans.ApiResponse, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object) */ @Override public IReadWriteStream<ApiResponse> getResponseDataHandler(final ApiResponse response, IPolicyContext context, Object policyConfiguration) { final String callbackFunctionName = (String) context.getAttribute(CALLBACK_FUNCTION_NAME, null); if (callbackFunctionName != null) {
HttpHeaders httpHeaders = new HttpHeaders(response.getHeaders());
apiman/apiman-plugins
timeout-policy/src/test/java/io/apiman/plugins/timeoutpolicy/TimeoutPolicyTest.java
// Path: timeout-policy/src/main/java/io/apiman/plugins/timeoutpolicy/beans/TimeoutConfigBean.java // public class TimeoutConfigBean { // // @JsonProperty // private String timeoutConnect; // // @JsonProperty // private String timeoutRead; // // public String getTimeoutConnect() { // return timeoutConnect; // } // // public void setTimeoutConnect(String timeoutConnect) { // this.timeoutConnect = timeoutConnect; // } // // public String getTimeoutRead() { // return timeoutRead; // } // // public void setTimeoutRead(String timeoutRead) { // this.timeoutRead = timeoutRead; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.util.HashMap; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.plugins.timeoutpolicy.beans.TimeoutConfigBean; import io.apiman.test.policies.ApimanPolicyTest; import io.apiman.test.policies.BackEndApi; import io.apiman.test.policies.Configuration; import io.apiman.test.policies.IPolicyTestBackEndApi; import io.apiman.test.policies.PolicyFailureError; import io.apiman.test.policies.PolicyTestBackEndApiResponse; import io.apiman.test.policies.PolicyTestRequest; import io.apiman.test.policies.PolicyTestRequestType; import io.apiman.test.policies.PolicyTestResponse; import io.apiman.test.policies.TestingPolicy;
package io.apiman.plugins.timeoutpolicy; /** * @author William Beck {@literal <william.beck.pro@gmail.com>} */ @TestingPolicy(TimeoutPolicy.class) public class TimeoutPolicyTest extends ApimanPolicyTest { private TimeoutPolicy timeoutPolicy = new TimeoutPolicy(); /** * Control the type of the config bean */ @Test @Configuration("{\"timeoutConnect\" : \"1\", \"timeoutRead\" : \"1\" }") public void shouldReturnTimeoutConfigBean_onGetConfigurationClass() { // WHEN retrieving the configuration class Class<?> confClass = timeoutPolicy.getConfigurationClass(); // THEN it must be the payload bean config
// Path: timeout-policy/src/main/java/io/apiman/plugins/timeoutpolicy/beans/TimeoutConfigBean.java // public class TimeoutConfigBean { // // @JsonProperty // private String timeoutConnect; // // @JsonProperty // private String timeoutRead; // // public String getTimeoutConnect() { // return timeoutConnect; // } // // public void setTimeoutConnect(String timeoutConnect) { // this.timeoutConnect = timeoutConnect; // } // // public String getTimeoutRead() { // return timeoutRead; // } // // public void setTimeoutRead(String timeoutRead) { // this.timeoutRead = timeoutRead; // } // // } // Path: timeout-policy/src/test/java/io/apiman/plugins/timeoutpolicy/TimeoutPolicyTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.util.HashMap; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.plugins.timeoutpolicy.beans.TimeoutConfigBean; import io.apiman.test.policies.ApimanPolicyTest; import io.apiman.test.policies.BackEndApi; import io.apiman.test.policies.Configuration; import io.apiman.test.policies.IPolicyTestBackEndApi; import io.apiman.test.policies.PolicyFailureError; import io.apiman.test.policies.PolicyTestBackEndApiResponse; import io.apiman.test.policies.PolicyTestRequest; import io.apiman.test.policies.PolicyTestRequestType; import io.apiman.test.policies.PolicyTestResponse; import io.apiman.test.policies.TestingPolicy; package io.apiman.plugins.timeoutpolicy; /** * @author William Beck {@literal <william.beck.pro@gmail.com>} */ @TestingPolicy(TimeoutPolicy.class) public class TimeoutPolicyTest extends ApimanPolicyTest { private TimeoutPolicy timeoutPolicy = new TimeoutPolicy(); /** * Control the type of the config bean */ @Test @Configuration("{\"timeoutConnect\" : \"1\", \"timeoutRead\" : \"1\" }") public void shouldReturnTimeoutConfigBean_onGetConfigurationClass() { // WHEN retrieving the configuration class Class<?> confClass = timeoutPolicy.getConfigurationClass(); // THEN it must be the payload bean config
assertEquals(TimeoutConfigBean.class, confClass);
apiman/apiman-plugins
log-policy/src/main/java/io/apiman/plugins/log_policy/LogHeadersPolicy.java
// Path: log-policy/src/main/java/io/apiman/plugins/log_policy/beans/LogHeadersConfigBean.java // public class LogHeadersConfigBean { // // @JsonProperty // private LogHeadersDirectionType direction; // // /** // * Whether to log the request/response headers. // * Defaults to {@code true} for backwards compatibility. // */ // @JsonProperty // private boolean logHeaders = true; // // /** // * Whether to log the response status code. // */ // @JsonProperty // private boolean logStatusCode; // // /** // * Constructor. // */ // public LogHeadersConfigBean() { // } // // /** // * @return the direction // */ // public LogHeadersDirectionType getDirection() { // return direction; // } // // /** // * @param direction the direction to set // */ // public void setDirection(LogHeadersDirectionType direction) { // this.direction = direction; // } // // /** // * @return whether to log the headers // */ // public boolean isLogHeaders() { // return logHeaders; // } // // /** // * @return whether to log the status code // */ // public boolean isLogStatusCode() { // return logStatusCode; // } // } // // Path: log-policy/src/main/java/io/apiman/plugins/log_policy/beans/LogHeadersDirectionType.java // public enum LogHeadersDirectionType { // // request, response, both // // }
import io.apiman.common.logging.IApimanLogger; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.gateway.engine.beans.util.HeaderMap; import io.apiman.gateway.engine.policies.AbstractMappedPolicy; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.plugins.log_policy.beans.LogHeadersConfigBean; import io.apiman.plugins.log_policy.beans.LogHeadersDirectionType; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet;
/* * Copyright 2015 JBoss Inc * * 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 io.apiman.plugins.log_policy; /** * A policy that logs the headers of the HTTP request and HTTP response at the current position in the chain. * * @author ton.swieb@finalist.nl */ public class LogHeadersPolicy extends AbstractMappedPolicy<LogHeadersConfigBean> { private static enum HttpDirection { REQUEST("HTTP Request"), //$NON-NLS-1$ RESPONSE("HTTP Response"); //$NON-NLS-1$ private final String description; HttpDirection(String descr) { this.description = descr; } String getDescription() { return description; } }; public static final String ENDPOINT_ATTRIBUTE = "LogHeadersPolicy_EndpointAttribute"; //$NON-NLS-1$ /** * Constructor. */ public LogHeadersPolicy() { } /** * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#getConfigurationClass() */ @Override protected Class<LogHeadersConfigBean> getConfigurationClass() { return LogHeadersConfigBean.class; } /** * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#doApply(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.policy.IPolicyChain) */ @Override protected void doApply(ApiRequest request, IPolicyContext context, LogHeadersConfigBean config, IPolicyChain<ApiRequest> chain) { IApimanLogger logger = context.getLogger(getClass()); String endpoint = request.getApi().getEndpoint(); context.setAttribute(ENDPOINT_ATTRIBUTE, endpoint);
// Path: log-policy/src/main/java/io/apiman/plugins/log_policy/beans/LogHeadersConfigBean.java // public class LogHeadersConfigBean { // // @JsonProperty // private LogHeadersDirectionType direction; // // /** // * Whether to log the request/response headers. // * Defaults to {@code true} for backwards compatibility. // */ // @JsonProperty // private boolean logHeaders = true; // // /** // * Whether to log the response status code. // */ // @JsonProperty // private boolean logStatusCode; // // /** // * Constructor. // */ // public LogHeadersConfigBean() { // } // // /** // * @return the direction // */ // public LogHeadersDirectionType getDirection() { // return direction; // } // // /** // * @param direction the direction to set // */ // public void setDirection(LogHeadersDirectionType direction) { // this.direction = direction; // } // // /** // * @return whether to log the headers // */ // public boolean isLogHeaders() { // return logHeaders; // } // // /** // * @return whether to log the status code // */ // public boolean isLogStatusCode() { // return logStatusCode; // } // } // // Path: log-policy/src/main/java/io/apiman/plugins/log_policy/beans/LogHeadersDirectionType.java // public enum LogHeadersDirectionType { // // request, response, both // // } // Path: log-policy/src/main/java/io/apiman/plugins/log_policy/LogHeadersPolicy.java import io.apiman.common.logging.IApimanLogger; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.gateway.engine.beans.util.HeaderMap; import io.apiman.gateway.engine.policies.AbstractMappedPolicy; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.plugins.log_policy.beans.LogHeadersConfigBean; import io.apiman.plugins.log_policy.beans.LogHeadersDirectionType; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; /* * Copyright 2015 JBoss Inc * * 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 io.apiman.plugins.log_policy; /** * A policy that logs the headers of the HTTP request and HTTP response at the current position in the chain. * * @author ton.swieb@finalist.nl */ public class LogHeadersPolicy extends AbstractMappedPolicy<LogHeadersConfigBean> { private static enum HttpDirection { REQUEST("HTTP Request"), //$NON-NLS-1$ RESPONSE("HTTP Response"); //$NON-NLS-1$ private final String description; HttpDirection(String descr) { this.description = descr; } String getDescription() { return description; } }; public static final String ENDPOINT_ATTRIBUTE = "LogHeadersPolicy_EndpointAttribute"; //$NON-NLS-1$ /** * Constructor. */ public LogHeadersPolicy() { } /** * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#getConfigurationClass() */ @Override protected Class<LogHeadersConfigBean> getConfigurationClass() { return LogHeadersConfigBean.class; } /** * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#doApply(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.policy.IPolicyChain) */ @Override protected void doApply(ApiRequest request, IPolicyContext context, LogHeadersConfigBean config, IPolicyChain<ApiRequest> chain) { IApimanLogger logger = context.getLogger(getClass()); String endpoint = request.getApi().getEndpoint(); context.setAttribute(ENDPOINT_ATTRIBUTE, endpoint);
if (config.isLogHeaders() && config.getDirection() != LogHeadersDirectionType.response) {
apiman/apiman-plugins
keycloak-oauth-policy/src/main/java/io/apiman/plugins/keycloak_oauth_policy/failures/PolicyFailureFactory.java
// Path: keycloak-oauth-policy/src/main/java/io/apiman/plugins/keycloak_oauth_policy/Messages.java // public class Messages { // private static final String BUNDLE_NAME = "io.apiman.plugins.keycloak_oauth_policy.messages"; //$NON-NLS-1$ // // private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); // // private Messages() { // } // // public static String getString(String key) { // try { // return RESOURCE_BUNDLE.getString(key); // } catch (MissingResourceException e) { // return '!' + key + '!'; // } // } // }
import org.keycloak.common.VerificationException; import io.apiman.gateway.engine.beans.PolicyFailure; import io.apiman.gateway.engine.beans.PolicyFailureType; import io.apiman.gateway.engine.components.IPolicyFailureFactoryComponent; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.plugins.keycloak_oauth_policy.Messages;
/* * Copyright 2015 JBoss Inc * * 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 io.apiman.plugins.keycloak_oauth_policy.failures; /** * Policy failures * * @author Marc Savy {@literal <msavy@redhat.com>} */ public class PolicyFailureFactory { private static final int HTTP_UNAUTHORIZED = 401; private static final int AUTH_MISSING_ROLE = 11001; private static final int AUTH_BLACKLISTED_TOKEN = 11002; private static final int AUTH_NO_TRANSPORT_SECURITY = 11003; private static final int AUTH_VERIFICATION_ERROR = 11004; private static final int AUTH_NOT_PROVIDED = 11005; public PolicyFailure noAuthenticationProvided(IPolicyContext context) { return createAuthenticationPolicyFailure(context, AUTH_NOT_PROVIDED,
// Path: keycloak-oauth-policy/src/main/java/io/apiman/plugins/keycloak_oauth_policy/Messages.java // public class Messages { // private static final String BUNDLE_NAME = "io.apiman.plugins.keycloak_oauth_policy.messages"; //$NON-NLS-1$ // // private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); // // private Messages() { // } // // public static String getString(String key) { // try { // return RESOURCE_BUNDLE.getString(key); // } catch (MissingResourceException e) { // return '!' + key + '!'; // } // } // } // Path: keycloak-oauth-policy/src/main/java/io/apiman/plugins/keycloak_oauth_policy/failures/PolicyFailureFactory.java import org.keycloak.common.VerificationException; import io.apiman.gateway.engine.beans.PolicyFailure; import io.apiman.gateway.engine.beans.PolicyFailureType; import io.apiman.gateway.engine.components.IPolicyFailureFactoryComponent; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.plugins.keycloak_oauth_policy.Messages; /* * Copyright 2015 JBoss Inc * * 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 io.apiman.plugins.keycloak_oauth_policy.failures; /** * Policy failures * * @author Marc Savy {@literal <msavy@redhat.com>} */ public class PolicyFailureFactory { private static final int HTTP_UNAUTHORIZED = 401; private static final int AUTH_MISSING_ROLE = 11001; private static final int AUTH_BLACKLISTED_TOKEN = 11002; private static final int AUTH_NO_TRANSPORT_SECURITY = 11003; private static final int AUTH_VERIFICATION_ERROR = 11004; private static final int AUTH_NOT_PROVIDED = 11005; public PolicyFailure noAuthenticationProvided(IPolicyContext context) { return createAuthenticationPolicyFailure(context, AUTH_NOT_PROVIDED,
Messages.getString("KeycloakOauthPolicy.NoTokenGiven")); //$NON-NLS-1$
apiman/apiman-plugins
cors-policy/src/main/java/io/apiman/plugins/cors_policy/CorsConfigBean.java
// Path: cors-policy/src/main/java/io/apiman/plugins/cors_policy/util/InsensitiveLinkedHashSet.java // public class InsensitiveLinkedHashSet extends LinkedHashSet<String> implements Serializable, Set<String> { // // private static final long serialVersionUID = -3273143085866100001L; // private Set<String> innerSet = new HashSet<>(); // // public InsensitiveLinkedHashSet() { // super(); // } // // public InsensitiveLinkedHashSet(Collection<? extends String> entries) { // super(entries.size()); // addAll(entries); // } // // @Override // public boolean add(String entry) { // if (entry == null || innerSet.contains(entry.toLowerCase())) { // return false; // } // // innerSet.add(entry.toLowerCase()); // return super.add(entry); // } // // @Override // public boolean addAll(Collection<? extends String> entries) { // boolean success = true; // // for (String entry : entries) { // success = success && add(entry); // } // // return success; // } // // @Override // public boolean containsAll(Collection<?> entries) { // boolean success = true; // // for (Object entry : entries) { // if (entry instanceof String) { // success = success && contains(entry); // } // } // // return success; // } // // @Override // public boolean contains(Object candidate) { // if (candidate == null || !(candidate instanceof String)) // return false; // // return innerSet.contains(((String) candidate).toLowerCase()); // } // // }
import io.apiman.plugins.cors_policy.util.HttpHelper; import io.apiman.plugins.cors_policy.util.InsensitiveLinkedHashSet; import java.io.Serializable; import java.util.LinkedHashSet; import java.util.Set; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/* * Copyright 2015 JBoss Inc * * 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 io.apiman.plugins.cors_policy; /** * CORS Policy Configuration * * @author Marc Savy {@literal <msavy@redhat.com>} */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "errorOnCorsFailure", "allowOrigin", "allowCredentials", "exposeHeaders", "allowHeaders", "allowMethods", "maxAge" }) public class CorsConfigBean implements Serializable { private static final long serialVersionUID = 6655123241544127400L; /** * Terminate on CORS error * <p> * When true, any request that fails CORS validation will be terminated with an appropriate error. When * false, the request will still be sent to the backend API, but the browser will be left to enforce * the CORS failure. In both cases valid CORS headers will be set. * */ @JsonProperty("errorOnCorsFailure") private boolean errorOnCorsFailure = true; /** * Access-Control-Allow-Origin * <p> * List of origins permitted to make CORS requests through the gateway. By default same-origin is * permitted, and cross-origin is forbidden. An entry of * permits all CORS requests. * */ @JsonProperty("allowOrigin")
// Path: cors-policy/src/main/java/io/apiman/plugins/cors_policy/util/InsensitiveLinkedHashSet.java // public class InsensitiveLinkedHashSet extends LinkedHashSet<String> implements Serializable, Set<String> { // // private static final long serialVersionUID = -3273143085866100001L; // private Set<String> innerSet = new HashSet<>(); // // public InsensitiveLinkedHashSet() { // super(); // } // // public InsensitiveLinkedHashSet(Collection<? extends String> entries) { // super(entries.size()); // addAll(entries); // } // // @Override // public boolean add(String entry) { // if (entry == null || innerSet.contains(entry.toLowerCase())) { // return false; // } // // innerSet.add(entry.toLowerCase()); // return super.add(entry); // } // // @Override // public boolean addAll(Collection<? extends String> entries) { // boolean success = true; // // for (String entry : entries) { // success = success && add(entry); // } // // return success; // } // // @Override // public boolean containsAll(Collection<?> entries) { // boolean success = true; // // for (Object entry : entries) { // if (entry instanceof String) { // success = success && contains(entry); // } // } // // return success; // } // // @Override // public boolean contains(Object candidate) { // if (candidate == null || !(candidate instanceof String)) // return false; // // return innerSet.contains(((String) candidate).toLowerCase()); // } // // } // Path: cors-policy/src/main/java/io/apiman/plugins/cors_policy/CorsConfigBean.java import io.apiman.plugins.cors_policy.util.HttpHelper; import io.apiman.plugins.cors_policy.util.InsensitiveLinkedHashSet; import java.io.Serializable; import java.util.LinkedHashSet; import java.util.Set; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /* * Copyright 2015 JBoss Inc * * 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 io.apiman.plugins.cors_policy; /** * CORS Policy Configuration * * @author Marc Savy {@literal <msavy@redhat.com>} */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "errorOnCorsFailure", "allowOrigin", "allowCredentials", "exposeHeaders", "allowHeaders", "allowMethods", "maxAge" }) public class CorsConfigBean implements Serializable { private static final long serialVersionUID = 6655123241544127400L; /** * Terminate on CORS error * <p> * When true, any request that fails CORS validation will be terminated with an appropriate error. When * false, the request will still be sent to the backend API, but the browser will be left to enforce * the CORS failure. In both cases valid CORS headers will be set. * */ @JsonProperty("errorOnCorsFailure") private boolean errorOnCorsFailure = true; /** * Access-Control-Allow-Origin * <p> * List of origins permitted to make CORS requests through the gateway. By default same-origin is * permitted, and cross-origin is forbidden. An entry of * permits all CORS requests. * */ @JsonProperty("allowOrigin")
@JsonDeserialize(as = InsensitiveLinkedHashSet.class)
apiman/apiman-plugins
jsonp-policy/src/test/java/io/apiman/plugins/jsonp_policy/JsonpPolicyTest.java
// Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/beans/JsonpConfigBean.java // public class JsonpConfigBean { // // @JsonProperty // private String callbackParamName; // // /** // * @return the parameter name used to specify the callback function // */ // public String getCallbackParamName() { // return callbackParamName; // } // // /** // * @param callbackParamName the parameter name used to specify the callback function // */ // public void setCallbackParamName(String callbackParamName) { // this.callbackParamName = callbackParamName; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.mockito.Matchers.refEq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import io.apiman.gateway.engine.async.IAsyncHandler; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.gateway.engine.beans.util.QueryMap; import io.apiman.gateway.engine.components.IBufferFactoryComponent; import io.apiman.gateway.engine.io.ByteBuffer; import io.apiman.gateway.engine.io.IApimanBuffer; import io.apiman.gateway.engine.io.IReadWriteStream; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.gateway.engine.policy.PolicyContextImpl; import io.apiman.plugins.jsonp_policy.beans.JsonpConfigBean; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy;
package io.apiman.plugins.jsonp_policy; @SuppressWarnings("nls") public class JsonpPolicyTest { private JsonpPolicy jsonpPolicy; @Spy private IPolicyContext sContext = new PolicyContextImpl(null); @Before public void setUp() { MockitoAnnotations.initMocks(this); Mockito.doReturn(new TestBufferFactory()).when(sContext).getComponent(IBufferFactoryComponent.class); jsonpPolicy = new JsonpPolicy(); } @Test public void testParseEmptyConfiguration() { // given String config = "{}"; // when
// Path: jsonp-policy/src/main/java/io/apiman/plugins/jsonp_policy/beans/JsonpConfigBean.java // public class JsonpConfigBean { // // @JsonProperty // private String callbackParamName; // // /** // * @return the parameter name used to specify the callback function // */ // public String getCallbackParamName() { // return callbackParamName; // } // // /** // * @param callbackParamName the parameter name used to specify the callback function // */ // public void setCallbackParamName(String callbackParamName) { // this.callbackParamName = callbackParamName; // } // } // Path: jsonp-policy/src/test/java/io/apiman/plugins/jsonp_policy/JsonpPolicyTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.mockito.Matchers.refEq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import io.apiman.gateway.engine.async.IAsyncHandler; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.ApiResponse; import io.apiman.gateway.engine.beans.util.QueryMap; import io.apiman.gateway.engine.components.IBufferFactoryComponent; import io.apiman.gateway.engine.io.ByteBuffer; import io.apiman.gateway.engine.io.IApimanBuffer; import io.apiman.gateway.engine.io.IReadWriteStream; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import io.apiman.gateway.engine.policy.PolicyContextImpl; import io.apiman.plugins.jsonp_policy.beans.JsonpConfigBean; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; package io.apiman.plugins.jsonp_policy; @SuppressWarnings("nls") public class JsonpPolicyTest { private JsonpPolicy jsonpPolicy; @Spy private IPolicyContext sContext = new PolicyContextImpl(null); @Before public void setUp() { MockitoAnnotations.initMocks(this); Mockito.doReturn(new TestBufferFactory()).when(sContext).getComponent(IBufferFactoryComponent.class); jsonpPolicy = new JsonpPolicy(); } @Test public void testParseEmptyConfiguration() { // given String config = "{}"; // when
JsonpConfigBean jsonpConfig = jsonpPolicy.parseConfiguration(config);
neilbeveridge/zuul-netty
netty-framework-plugins/src/main/java/com/netflix/zuul/proxy/framework/plugins/GlobalRewriteRequestHandler.java
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/HttpRequestHandlerFactory.java // public interface HttpRequestHandlerFactory { // // HttpRequestHandler getInstance(String tag, com.netflix.zuul.proxy.framework.api.Interrupts interrupts); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/Interrupts.java // public interface Interrupts { // // void movedPermanently (String location); // void temporaryRedirect (String location); // // }
import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; import com.netflix.zuul.proxy.framework.api.HttpRequestHandler; import com.netflix.zuul.proxy.framework.api.HttpRequestHandlerFactory; import com.netflix.zuul.proxy.framework.api.Interrupts;
package com.netflix.zuul.proxy.framework.plugins; public class GlobalRewriteRequestHandler implements HttpRequestHandler { @Override
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/HttpRequestHandlerFactory.java // public interface HttpRequestHandlerFactory { // // HttpRequestHandler getInstance(String tag, com.netflix.zuul.proxy.framework.api.Interrupts interrupts); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/Interrupts.java // public interface Interrupts { // // void movedPermanently (String location); // void temporaryRedirect (String location); // // } // Path: netty-framework-plugins/src/main/java/com/netflix/zuul/proxy/framework/plugins/GlobalRewriteRequestHandler.java import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; import com.netflix.zuul.proxy.framework.api.HttpRequestHandler; import com.netflix.zuul.proxy.framework.api.HttpRequestHandlerFactory; import com.netflix.zuul.proxy.framework.api.Interrupts; package com.netflix.zuul.proxy.framework.plugins; public class GlobalRewriteRequestHandler implements HttpRequestHandler { @Override
public void requestReceived(FrameworkHttpRequest request) {
neilbeveridge/zuul-netty
netty-framework-plugins/src/main/java/com/netflix/zuul/proxy/framework/plugins/GlobalRewriteRequestHandler.java
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/HttpRequestHandlerFactory.java // public interface HttpRequestHandlerFactory { // // HttpRequestHandler getInstance(String tag, com.netflix.zuul.proxy.framework.api.Interrupts interrupts); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/Interrupts.java // public interface Interrupts { // // void movedPermanently (String location); // void temporaryRedirect (String location); // // }
import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; import com.netflix.zuul.proxy.framework.api.HttpRequestHandler; import com.netflix.zuul.proxy.framework.api.HttpRequestHandlerFactory; import com.netflix.zuul.proxy.framework.api.Interrupts;
package com.netflix.zuul.proxy.framework.plugins; public class GlobalRewriteRequestHandler implements HttpRequestHandler { @Override public void requestReceived(FrameworkHttpRequest request) { switch (request.getUri()) { case "/foo": request.setUri(String.format("/bar")); } }
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/HttpRequestHandlerFactory.java // public interface HttpRequestHandlerFactory { // // HttpRequestHandler getInstance(String tag, com.netflix.zuul.proxy.framework.api.Interrupts interrupts); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/Interrupts.java // public interface Interrupts { // // void movedPermanently (String location); // void temporaryRedirect (String location); // // } // Path: netty-framework-plugins/src/main/java/com/netflix/zuul/proxy/framework/plugins/GlobalRewriteRequestHandler.java import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; import com.netflix.zuul.proxy.framework.api.HttpRequestHandler; import com.netflix.zuul.proxy.framework.api.HttpRequestHandlerFactory; import com.netflix.zuul.proxy.framework.api.Interrupts; package com.netflix.zuul.proxy.framework.plugins; public class GlobalRewriteRequestHandler implements HttpRequestHandler { @Override public void requestReceived(FrameworkHttpRequest request) { switch (request.getUri()) { case "/foo": request.setUri(String.format("/bar")); } }
public static final HttpRequestHandlerFactory FACTORY = new HttpRequestHandlerFactory() {
neilbeveridge/zuul-netty
netty-framework-plugins/src/main/java/com/netflix/zuul/proxy/framework/plugins/GlobalRewriteRequestHandler.java
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/HttpRequestHandlerFactory.java // public interface HttpRequestHandlerFactory { // // HttpRequestHandler getInstance(String tag, com.netflix.zuul.proxy.framework.api.Interrupts interrupts); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/Interrupts.java // public interface Interrupts { // // void movedPermanently (String location); // void temporaryRedirect (String location); // // }
import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; import com.netflix.zuul.proxy.framework.api.HttpRequestHandler; import com.netflix.zuul.proxy.framework.api.HttpRequestHandlerFactory; import com.netflix.zuul.proxy.framework.api.Interrupts;
package com.netflix.zuul.proxy.framework.plugins; public class GlobalRewriteRequestHandler implements HttpRequestHandler { @Override public void requestReceived(FrameworkHttpRequest request) { switch (request.getUri()) { case "/foo": request.setUri(String.format("/bar")); } } public static final HttpRequestHandlerFactory FACTORY = new HttpRequestHandlerFactory() { @Override
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/HttpRequestHandlerFactory.java // public interface HttpRequestHandlerFactory { // // HttpRequestHandler getInstance(String tag, com.netflix.zuul.proxy.framework.api.Interrupts interrupts); // // } // // Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/Interrupts.java // public interface Interrupts { // // void movedPermanently (String location); // void temporaryRedirect (String location); // // } // Path: netty-framework-plugins/src/main/java/com/netflix/zuul/proxy/framework/plugins/GlobalRewriteRequestHandler.java import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; import com.netflix.zuul.proxy.framework.api.HttpRequestHandler; import com.netflix.zuul.proxy.framework.api.HttpRequestHandlerFactory; import com.netflix.zuul.proxy.framework.api.Interrupts; package com.netflix.zuul.proxy.framework.plugins; public class GlobalRewriteRequestHandler implements HttpRequestHandler { @Override public void requestReceived(FrameworkHttpRequest request) { switch (request.getUri()) { case "/foo": request.setUri(String.format("/bar")); } } public static final HttpRequestHandlerFactory FACTORY = new HttpRequestHandlerFactory() { @Override
public HttpRequestHandler getInstance(String tag, Interrupts actionCallback) {
neilbeveridge/zuul-netty
netty-server/src/main/java/com/netflix/zuul/proxy/CommonHttpPipeline.java
// Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/FiltersListener.java // public interface FiltersListener extends EventListener { // // /** // * @param filterPath // * @param filter // */ // void filterAdded(Path filterPath, ZuulFilter filter); // // // /** // * // * @param filterPath // * @param filter // */ // void filterRemoved(Path filterPath, ZuulFilter filter); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilter.java // public interface ZuulFilter extends Ordered, Comparable<ZuulFilter> { // // /** // * @return // */ // String type(); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulPostFilter.java // public interface ZuulPostFilter extends ZuulFilter, HttpResponseHandler { // // boolean shouldFilter(FrameworkHttpRequest request, FrameworkHttpResponse response); // // }
import com.netflix.zuul.netty.filter.FiltersListener; import com.netflix.zuul.netty.filter.ZuulFilter; import com.netflix.zuul.netty.filter.ZuulPostFilter; import com.netflix.zuul.netty.filter.ZuulPreFilter; import com.netflix.zuul.proxy.core.CommonsConnectionPool; import com.netflix.zuul.proxy.core.ConnectionPool; import com.netflix.zuul.proxy.framework.plugins.LoggingResponseHandler; import com.netflix.zuul.proxy.handler.*; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
package com.netflix.zuul.proxy; public class CommonHttpPipeline implements ChannelPipelineFactory, FiltersListener { private static final Logger LOG = LoggerFactory.getLogger(CommonHttpPipeline.class); private final ConcurrentMap<ZuulPreFilter, Path> preFilters = new ConcurrentSkipListMap<>();
// Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/FiltersListener.java // public interface FiltersListener extends EventListener { // // /** // * @param filterPath // * @param filter // */ // void filterAdded(Path filterPath, ZuulFilter filter); // // // /** // * // * @param filterPath // * @param filter // */ // void filterRemoved(Path filterPath, ZuulFilter filter); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilter.java // public interface ZuulFilter extends Ordered, Comparable<ZuulFilter> { // // /** // * @return // */ // String type(); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulPostFilter.java // public interface ZuulPostFilter extends ZuulFilter, HttpResponseHandler { // // boolean shouldFilter(FrameworkHttpRequest request, FrameworkHttpResponse response); // // } // Path: netty-server/src/main/java/com/netflix/zuul/proxy/CommonHttpPipeline.java import com.netflix.zuul.netty.filter.FiltersListener; import com.netflix.zuul.netty.filter.ZuulFilter; import com.netflix.zuul.netty.filter.ZuulPostFilter; import com.netflix.zuul.netty.filter.ZuulPreFilter; import com.netflix.zuul.proxy.core.CommonsConnectionPool; import com.netflix.zuul.proxy.core.ConnectionPool; import com.netflix.zuul.proxy.framework.plugins.LoggingResponseHandler; import com.netflix.zuul.proxy.handler.*; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; package com.netflix.zuul.proxy; public class CommonHttpPipeline implements ChannelPipelineFactory, FiltersListener { private static final Logger LOG = LoggerFactory.getLogger(CommonHttpPipeline.class); private final ConcurrentMap<ZuulPreFilter, Path> preFilters = new ConcurrentSkipListMap<>();
private final ConcurrentMap<ZuulPostFilter, Path> postFilters = new ConcurrentSkipListMap<>();
neilbeveridge/zuul-netty
netty-server/src/main/java/com/netflix/zuul/proxy/CommonHttpPipeline.java
// Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/FiltersListener.java // public interface FiltersListener extends EventListener { // // /** // * @param filterPath // * @param filter // */ // void filterAdded(Path filterPath, ZuulFilter filter); // // // /** // * // * @param filterPath // * @param filter // */ // void filterRemoved(Path filterPath, ZuulFilter filter); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilter.java // public interface ZuulFilter extends Ordered, Comparable<ZuulFilter> { // // /** // * @return // */ // String type(); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulPostFilter.java // public interface ZuulPostFilter extends ZuulFilter, HttpResponseHandler { // // boolean shouldFilter(FrameworkHttpRequest request, FrameworkHttpResponse response); // // }
import com.netflix.zuul.netty.filter.FiltersListener; import com.netflix.zuul.netty.filter.ZuulFilter; import com.netflix.zuul.netty.filter.ZuulPostFilter; import com.netflix.zuul.netty.filter.ZuulPreFilter; import com.netflix.zuul.proxy.core.CommonsConnectionPool; import com.netflix.zuul.proxy.core.ConnectionPool; import com.netflix.zuul.proxy.framework.plugins.LoggingResponseHandler; import com.netflix.zuul.proxy.handler.*; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
//response handlers addZuulPostFilters(pipeline, postFilters); pipeline.addLast("app-http-response-logger", HTTP_RESPONSE_LOGGER); //request handlers addZuulPreFilters(pipeline, preFilters); //proxy pipeline.addLast("proxy", new HttpProxyHandler(outboundConnectionPool, IS_REQUEST_CHUNKED_ENABLED)); return pipeline; } private void addZuulPostFilters(ChannelPipeline pipeline, ConcurrentMap<ZuulPostFilter, Path> filters) { for (Map.Entry<ZuulPostFilter, Path> entry : filters.entrySet()) { String name = entry.getValue().toString(); pipeline.addLast(name, new HttpResponseFrameworkHandler(name, entry.getKey())); } } private void addZuulPreFilters(ChannelPipeline pipeline, ConcurrentMap<ZuulPreFilter, Path> filters) { for (Map.Entry<ZuulPreFilter, Path> entry : filters.entrySet()) { String name = entry.getValue().toString(); pipeline.addLast(name, new HttpRequestFrameworkHandler(name, entry.getKey())); } } @Override
// Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/FiltersListener.java // public interface FiltersListener extends EventListener { // // /** // * @param filterPath // * @param filter // */ // void filterAdded(Path filterPath, ZuulFilter filter); // // // /** // * // * @param filterPath // * @param filter // */ // void filterRemoved(Path filterPath, ZuulFilter filter); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilter.java // public interface ZuulFilter extends Ordered, Comparable<ZuulFilter> { // // /** // * @return // */ // String type(); // // } // // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulPostFilter.java // public interface ZuulPostFilter extends ZuulFilter, HttpResponseHandler { // // boolean shouldFilter(FrameworkHttpRequest request, FrameworkHttpResponse response); // // } // Path: netty-server/src/main/java/com/netflix/zuul/proxy/CommonHttpPipeline.java import com.netflix.zuul.netty.filter.FiltersListener; import com.netflix.zuul.netty.filter.ZuulFilter; import com.netflix.zuul.netty.filter.ZuulPostFilter; import com.netflix.zuul.netty.filter.ZuulPreFilter; import com.netflix.zuul.proxy.core.CommonsConnectionPool; import com.netflix.zuul.proxy.core.ConnectionPool; import com.netflix.zuul.proxy.framework.plugins.LoggingResponseHandler; import com.netflix.zuul.proxy.handler.*; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; //response handlers addZuulPostFilters(pipeline, postFilters); pipeline.addLast("app-http-response-logger", HTTP_RESPONSE_LOGGER); //request handlers addZuulPreFilters(pipeline, preFilters); //proxy pipeline.addLast("proxy", new HttpProxyHandler(outboundConnectionPool, IS_REQUEST_CHUNKED_ENABLED)); return pipeline; } private void addZuulPostFilters(ChannelPipeline pipeline, ConcurrentMap<ZuulPostFilter, Path> filters) { for (Map.Entry<ZuulPostFilter, Path> entry : filters.entrySet()) { String name = entry.getValue().toString(); pipeline.addLast(name, new HttpResponseFrameworkHandler(name, entry.getKey())); } } private void addZuulPreFilters(ChannelPipeline pipeline, ConcurrentMap<ZuulPreFilter, Path> filters) { for (Map.Entry<ZuulPreFilter, Path> entry : filters.entrySet()) { String name = entry.getValue().toString(); pipeline.addLast(name, new HttpRequestFrameworkHandler(name, entry.getKey())); } } @Override
public void filterAdded(Path filterPath, ZuulFilter filter) {
neilbeveridge/zuul-netty
zuul-core/src/main/java/com/netflix/zuul/netty/filter/AbstractZuulPreFilter.java
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // }
import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest;
package com.netflix.zuul.netty.filter; /** * @author HWEB */ public abstract class AbstractZuulPreFilter implements ZuulPreFilter { private final String type = "pre"; private final int order; public AbstractZuulPreFilter(int order) { this.order = order; } @Override public String type() { return type; } @Override public int order() { return order; } @Override
// Path: netty-framework-api/src/main/java/com/netflix/zuul/proxy/framework/api/FrameworkHttpRequest.java // public interface FrameworkHttpRequest { // // /** // * Returns the method of this request. // */ // HttpMethod getMethod(); // // /** // * Returns the URI (or path) of this request. // */ // String getUri(); // // /** // * Sets the URI (or path) of this request. // */ // void setUri(String uri); // // /** // * Returns the header value with the specified header name. If there are // * more than one header value for the specified header name, the first // * value is returned. // * // * @return the header value or {@code null} if there is no such header // */ // String getHeader(String name); // // /** // * Returns {@code true} if and only if there is a header with the specified // * header name. // */ // boolean containsHeader(String name); // // /** // * Adds a new header with the specified name and value. // */ // void addHeader(String name, Object value); // // /** // * Returns the all header names and values that this message contains. // * // * @return the {@link List} of the header name-value pairs. An empty list // * if there is no header in this message. // */ // List<Map.Entry<String, String>> getHeaders(); // // } // Path: zuul-core/src/main/java/com/netflix/zuul/netty/filter/AbstractZuulPreFilter.java import com.netflix.zuul.proxy.framework.api.FrameworkHttpRequest; package com.netflix.zuul.netty.filter; /** * @author HWEB */ public abstract class AbstractZuulPreFilter implements ZuulPreFilter { private final String type = "pre"; private final int order; public AbstractZuulPreFilter(int order) { this.order = order; } @Override public String type() { return type; } @Override public int order() { return order; } @Override
public boolean shouldFilter(FrameworkHttpRequest request) {
neilbeveridge/zuul-netty
netty-server/src/main/java/com/netflix/zuul/proxy/HttpOutboundPipeline.java
// Path: netty-server/src/main/java/com/netflix/zuul/proxy/handler/IdleChannelWatchdog.java // public class IdleChannelWatchdog extends IdleStateAwareChannelHandler { // private static final Logger LOG = LoggerFactory.getLogger(IdleChannelWatchdog.class); // // private final String channelName; // // public IdleChannelWatchdog (String channelName) { // this.channelName = channelName; // } // // @Override // public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception { // LOG.info("closing {} channel after {} event was intercepted", channelName, e.getState().toString()); // // e.getChannel().close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // if (future.isSuccess()) { // LOG.info("{} channel closed cleanly", channelName); // } else { // LOG.info("{} channel failed to close cleanly", channelName); // } // } // }); // } // // }
import com.netflix.zuul.proxy.handler.ClientTimingHandler; import com.netflix.zuul.proxy.handler.ExceptionSurfacerHandler; import com.netflix.zuul.proxy.handler.IdleChannelWatchdog; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpContentDecompressor; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.jboss.netty.handler.logging.LoggingHandler; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.logging.InternalLogLevel; import org.jboss.netty.util.Timer; import static org.jboss.netty.channel.Channels.pipeline;
package com.netflix.zuul.proxy; public class HttpOutboundPipeline implements ChannelPipelineFactory { private static final int RESPONSE_MAX_INITIAL_LINE_LENGTH = 4096; private static final int RESPONSE_MAX_HEADER_SIZE = (1024*8); private static final int RESPONSE_MAX_CHUNK_SIZE = (1024*8); //seconds until the TCP connection will close private static final int IDLE_TIMEOUT_READER = 0; private static final int IDLE_TIMEOUT_WRITER = 0; private static final int IDLE_TIMEOUT_BOTH = 10; private static final ChannelHandler EXCEPTION_SURFACER = new ExceptionSurfacerHandler(); private final ChannelHandler IDLE_STATE_HANDLER; public HttpOutboundPipeline (Timer timer) { IDLE_STATE_HANDLER = new IdleStateHandler(timer, IDLE_TIMEOUT_READER, IDLE_TIMEOUT_WRITER, IDLE_TIMEOUT_BOTH); } @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("idle-detection", IDLE_STATE_HANDLER); pipeline.addLast("logging", new LoggingHandler(InternalLogLevel.DEBUG)); pipeline.addLast("http-deflater", new HttpContentCompressor()); pipeline.addLast("decoder", new HttpResponseDecoder(RESPONSE_MAX_INITIAL_LINE_LENGTH, RESPONSE_MAX_HEADER_SIZE, RESPONSE_MAX_CHUNK_SIZE)); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("http-inflater", new HttpContentDecompressor()); pipeline.addLast("remote-hop-timer", new ClientTimingHandler("outbound")); pipeline.addLast("exception-surfacer", EXCEPTION_SURFACER);
// Path: netty-server/src/main/java/com/netflix/zuul/proxy/handler/IdleChannelWatchdog.java // public class IdleChannelWatchdog extends IdleStateAwareChannelHandler { // private static final Logger LOG = LoggerFactory.getLogger(IdleChannelWatchdog.class); // // private final String channelName; // // public IdleChannelWatchdog (String channelName) { // this.channelName = channelName; // } // // @Override // public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception { // LOG.info("closing {} channel after {} event was intercepted", channelName, e.getState().toString()); // // e.getChannel().close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // if (future.isSuccess()) { // LOG.info("{} channel closed cleanly", channelName); // } else { // LOG.info("{} channel failed to close cleanly", channelName); // } // } // }); // } // // } // Path: netty-server/src/main/java/com/netflix/zuul/proxy/HttpOutboundPipeline.java import com.netflix.zuul.proxy.handler.ClientTimingHandler; import com.netflix.zuul.proxy.handler.ExceptionSurfacerHandler; import com.netflix.zuul.proxy.handler.IdleChannelWatchdog; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpContentDecompressor; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.jboss.netty.handler.logging.LoggingHandler; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.logging.InternalLogLevel; import org.jboss.netty.util.Timer; import static org.jboss.netty.channel.Channels.pipeline; package com.netflix.zuul.proxy; public class HttpOutboundPipeline implements ChannelPipelineFactory { private static final int RESPONSE_MAX_INITIAL_LINE_LENGTH = 4096; private static final int RESPONSE_MAX_HEADER_SIZE = (1024*8); private static final int RESPONSE_MAX_CHUNK_SIZE = (1024*8); //seconds until the TCP connection will close private static final int IDLE_TIMEOUT_READER = 0; private static final int IDLE_TIMEOUT_WRITER = 0; private static final int IDLE_TIMEOUT_BOTH = 10; private static final ChannelHandler EXCEPTION_SURFACER = new ExceptionSurfacerHandler(); private final ChannelHandler IDLE_STATE_HANDLER; public HttpOutboundPipeline (Timer timer) { IDLE_STATE_HANDLER = new IdleStateHandler(timer, IDLE_TIMEOUT_READER, IDLE_TIMEOUT_WRITER, IDLE_TIMEOUT_BOTH); } @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("idle-detection", IDLE_STATE_HANDLER); pipeline.addLast("logging", new LoggingHandler(InternalLogLevel.DEBUG)); pipeline.addLast("http-deflater", new HttpContentCompressor()); pipeline.addLast("decoder", new HttpResponseDecoder(RESPONSE_MAX_INITIAL_LINE_LENGTH, RESPONSE_MAX_HEADER_SIZE, RESPONSE_MAX_CHUNK_SIZE)); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("http-inflater", new HttpContentDecompressor()); pipeline.addLast("remote-hop-timer", new ClientTimingHandler("outbound")); pipeline.addLast("exception-surfacer", EXCEPTION_SURFACER);
pipeline.addLast("idle-watchdog", new IdleChannelWatchdog("outbound"));
MCBans/MCBans
src/main/java/com/mcbans/client/BanStatusClient.java
// Path: src/main/java/com/mcbans/client/response/BanResponse.java // public class BanResponse { // private String uuid = ""; // private String name = ""; // private List<Ban> bans; // private double reputation; // private Ban ban; // private boolean mcbansStaff; // // public BanResponse(String uuid, String name, List<Ban> bans, double reputation, Ban ban, boolean mcbansStaff) { // this.uuid = uuid; // this.name = name; // this.bans = bans; // this.reputation = reputation; // this.ban = ban; // this.mcbansStaff = mcbansStaff; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public List<Ban> getBans() { // return bans; // } // // public void setBans(List<Ban> bans) { // this.bans = bans; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public Ban getBan() { // return ban; // } // // public void setBan(Ban ban) { // this.ban = ban; // } // // public boolean isMCBansStaff() { // return mcbansStaff; // } // // public void setMCBansStaff(boolean mcbansStaff) { // this.mcbansStaff = mcbansStaff; // } // // @Override // public String toString() { // String banList = ""; // if (bans.size() > 0) { // banList = bans.stream().map(ban -> // "\n " + ban.getReason() + // "\n id: " + ban.getId() + // ((ban.getServer()!=null)?"\n server: " + ban.getServer().getAddress():"") + // ((ban.getAdmin()!=null)?"\n admin: " + ban.getAdmin().getName() +" ( "+ban.getAdmin().getUuid()+" )":"") + // "\n repLoss: " + ban.getReputation() // ).collect(Collectors.joining()); // } // return "\n Name: " + name + "\n UUID: " + uuid + (isMCBansStaff() ? "\n This is a MCBans Staff" : "") + "\n Reputation: " + this.getReputation() + "\n Bans:" + banList + ((ban != null) ? "\n Ban Status:\n Type: " + ban.getType() + "\n Reason: " + ban.getReason() : ""); // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // }
import com.mcbans.client.response.BanResponse; import com.mcbans.domain.models.client.Ban; import com.mcbans.utils.*; import java.io.IOException; import java.util.List;
package com.mcbans.client; public class BanStatusClient extends Client{ public BanStatusClient(Client c) { super(c); } public BanStatusClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static BanStatusClient cast(Client client) { return new BanStatusClient(client); }
// Path: src/main/java/com/mcbans/client/response/BanResponse.java // public class BanResponse { // private String uuid = ""; // private String name = ""; // private List<Ban> bans; // private double reputation; // private Ban ban; // private boolean mcbansStaff; // // public BanResponse(String uuid, String name, List<Ban> bans, double reputation, Ban ban, boolean mcbansStaff) { // this.uuid = uuid; // this.name = name; // this.bans = bans; // this.reputation = reputation; // this.ban = ban; // this.mcbansStaff = mcbansStaff; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public List<Ban> getBans() { // return bans; // } // // public void setBans(List<Ban> bans) { // this.bans = bans; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public Ban getBan() { // return ban; // } // // public void setBan(Ban ban) { // this.ban = ban; // } // // public boolean isMCBansStaff() { // return mcbansStaff; // } // // public void setMCBansStaff(boolean mcbansStaff) { // this.mcbansStaff = mcbansStaff; // } // // @Override // public String toString() { // String banList = ""; // if (bans.size() > 0) { // banList = bans.stream().map(ban -> // "\n " + ban.getReason() + // "\n id: " + ban.getId() + // ((ban.getServer()!=null)?"\n server: " + ban.getServer().getAddress():"") + // ((ban.getAdmin()!=null)?"\n admin: " + ban.getAdmin().getName() +" ( "+ban.getAdmin().getUuid()+" )":"") + // "\n repLoss: " + ban.getReputation() // ).collect(Collectors.joining()); // } // return "\n Name: " + name + "\n UUID: " + uuid + (isMCBansStaff() ? "\n This is a MCBans Staff" : "") + "\n Reputation: " + this.getReputation() + "\n Bans:" + banList + ((ban != null) ? "\n Ban Status:\n Type: " + ban.getType() + "\n Reason: " + ban.getReason() : ""); // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // Path: src/main/java/com/mcbans/client/BanStatusClient.java import com.mcbans.client.response.BanResponse; import com.mcbans.domain.models.client.Ban; import com.mcbans.utils.*; import java.io.IOException; import java.util.List; package com.mcbans.client; public class BanStatusClient extends Client{ public BanStatusClient(Client c) { super(c); } public BanStatusClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static BanStatusClient cast(Client client) { return new BanStatusClient(client); }
public BanResponse banStatusByPlayerName(String playerName, String ipAddress, boolean loginRequest) throws IOException, ClassNotFoundException, TooLargeException {
MCBans/MCBans
src/main/java/com/mcbans/client/BanStatusClient.java
// Path: src/main/java/com/mcbans/client/response/BanResponse.java // public class BanResponse { // private String uuid = ""; // private String name = ""; // private List<Ban> bans; // private double reputation; // private Ban ban; // private boolean mcbansStaff; // // public BanResponse(String uuid, String name, List<Ban> bans, double reputation, Ban ban, boolean mcbansStaff) { // this.uuid = uuid; // this.name = name; // this.bans = bans; // this.reputation = reputation; // this.ban = ban; // this.mcbansStaff = mcbansStaff; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public List<Ban> getBans() { // return bans; // } // // public void setBans(List<Ban> bans) { // this.bans = bans; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public Ban getBan() { // return ban; // } // // public void setBan(Ban ban) { // this.ban = ban; // } // // public boolean isMCBansStaff() { // return mcbansStaff; // } // // public void setMCBansStaff(boolean mcbansStaff) { // this.mcbansStaff = mcbansStaff; // } // // @Override // public String toString() { // String banList = ""; // if (bans.size() > 0) { // banList = bans.stream().map(ban -> // "\n " + ban.getReason() + // "\n id: " + ban.getId() + // ((ban.getServer()!=null)?"\n server: " + ban.getServer().getAddress():"") + // ((ban.getAdmin()!=null)?"\n admin: " + ban.getAdmin().getName() +" ( "+ban.getAdmin().getUuid()+" )":"") + // "\n repLoss: " + ban.getReputation() // ).collect(Collectors.joining()); // } // return "\n Name: " + name + "\n UUID: " + uuid + (isMCBansStaff() ? "\n This is a MCBans Staff" : "") + "\n Reputation: " + this.getReputation() + "\n Bans:" + banList + ((ban != null) ? "\n Ban Status:\n Type: " + ban.getType() + "\n Reason: " + ban.getReason() : ""); // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // }
import com.mcbans.client.response.BanResponse; import com.mcbans.domain.models.client.Ban; import com.mcbans.utils.*; import java.io.IOException; import java.util.List;
} public BanStatusClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static BanStatusClient cast(Client client) { return new BanStatusClient(client); } public BanResponse banStatusByPlayerName(String playerName, String ipAddress, boolean loginRequest) throws IOException, ClassNotFoundException, TooLargeException { sendCommand(ServerMCBansCommands.BanStatusByPlayerName); WriteToOutputStream.writeString(getOutputStream(), playerName); WriteToOutputStream.writeString(getOutputStream(), ipAddress); WriteToOutputStream.writeBoolean(getOutputStream(), loginRequest); return banStatusResponseHandler(); } public BanResponse banStatusByPlayerUUID(String playerUUID, String ipAddress, boolean loginRequest) throws IOException, ClassNotFoundException, TooLargeException { sendCommand(ServerMCBansCommands.BanStatusByPlayerUUID); WriteToOutputStream.writeString(getOutputStream(), playerUUID); WriteToOutputStream.writeString(getOutputStream(), ipAddress); WriteToOutputStream.writeBoolean(getOutputStream(), loginRequest); return banStatusResponseHandler(); } public BanResponse banStatusResponseHandler() throws IOException, ClassNotFoundException, TooLargeException { Command command = getCommand(getInputStream()); switch (command.getCommand()){ case 10: String uuid = ReadFromInputStream.readString(getInputStream(), 32); String name = ReadFromInputStream.readString(getInputStream(), 128);
// Path: src/main/java/com/mcbans/client/response/BanResponse.java // public class BanResponse { // private String uuid = ""; // private String name = ""; // private List<Ban> bans; // private double reputation; // private Ban ban; // private boolean mcbansStaff; // // public BanResponse(String uuid, String name, List<Ban> bans, double reputation, Ban ban, boolean mcbansStaff) { // this.uuid = uuid; // this.name = name; // this.bans = bans; // this.reputation = reputation; // this.ban = ban; // this.mcbansStaff = mcbansStaff; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public List<Ban> getBans() { // return bans; // } // // public void setBans(List<Ban> bans) { // this.bans = bans; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public Ban getBan() { // return ban; // } // // public void setBan(Ban ban) { // this.ban = ban; // } // // public boolean isMCBansStaff() { // return mcbansStaff; // } // // public void setMCBansStaff(boolean mcbansStaff) { // this.mcbansStaff = mcbansStaff; // } // // @Override // public String toString() { // String banList = ""; // if (bans.size() > 0) { // banList = bans.stream().map(ban -> // "\n " + ban.getReason() + // "\n id: " + ban.getId() + // ((ban.getServer()!=null)?"\n server: " + ban.getServer().getAddress():"") + // ((ban.getAdmin()!=null)?"\n admin: " + ban.getAdmin().getName() +" ( "+ban.getAdmin().getUuid()+" )":"") + // "\n repLoss: " + ban.getReputation() // ).collect(Collectors.joining()); // } // return "\n Name: " + name + "\n UUID: " + uuid + (isMCBansStaff() ? "\n This is a MCBans Staff" : "") + "\n Reputation: " + this.getReputation() + "\n Bans:" + banList + ((ban != null) ? "\n Ban Status:\n Type: " + ban.getType() + "\n Reason: " + ban.getReason() : ""); // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // Path: src/main/java/com/mcbans/client/BanStatusClient.java import com.mcbans.client.response.BanResponse; import com.mcbans.domain.models.client.Ban; import com.mcbans.utils.*; import java.io.IOException; import java.util.List; } public BanStatusClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static BanStatusClient cast(Client client) { return new BanStatusClient(client); } public BanResponse banStatusByPlayerName(String playerName, String ipAddress, boolean loginRequest) throws IOException, ClassNotFoundException, TooLargeException { sendCommand(ServerMCBansCommands.BanStatusByPlayerName); WriteToOutputStream.writeString(getOutputStream(), playerName); WriteToOutputStream.writeString(getOutputStream(), ipAddress); WriteToOutputStream.writeBoolean(getOutputStream(), loginRequest); return banStatusResponseHandler(); } public BanResponse banStatusByPlayerUUID(String playerUUID, String ipAddress, boolean loginRequest) throws IOException, ClassNotFoundException, TooLargeException { sendCommand(ServerMCBansCommands.BanStatusByPlayerUUID); WriteToOutputStream.writeString(getOutputStream(), playerUUID); WriteToOutputStream.writeString(getOutputStream(), ipAddress); WriteToOutputStream.writeBoolean(getOutputStream(), loginRequest); return banStatusResponseHandler(); } public BanResponse banStatusResponseHandler() throws IOException, ClassNotFoundException, TooLargeException { Command command = getCommand(getInputStream()); switch (command.getCommand()){ case 10: String uuid = ReadFromInputStream.readString(getInputStream(), 32); String name = ReadFromInputStream.readString(getInputStream(), 128);
List<Ban> bans = ObjectSerializer.deserialize(ReadFromInputStream.readByteArrayToStream(getInputStream(), 1024*25)); // 25 KB
MCBans/MCBans
src/main/java/com/mcbans/client/PendingActionSyncClient.java
// Path: src/main/java/com/mcbans/utils/TooLargeException.java // public class TooLargeException extends Exception{ // }
import com.mcbans.utils.TooLargeException; import java.io.IOException; import java.nio.ByteBuffer;
package com.mcbans.client; public class PendingActionSyncClient extends Client{ public PendingActionSyncClient(Client c) { super(c); }
// Path: src/main/java/com/mcbans/utils/TooLargeException.java // public class TooLargeException extends Exception{ // } // Path: src/main/java/com/mcbans/client/PendingActionSyncClient.java import com.mcbans.utils.TooLargeException; import java.io.IOException; import java.nio.ByteBuffer; package com.mcbans.client; public class PendingActionSyncClient extends Client{ public PendingActionSyncClient(Client c) { super(c); }
public PendingActionSyncClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException {
MCBans/MCBans
src/main/java/com/mcbans/client/response/BanResponse.java
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // }
import com.mcbans.domain.models.client.Ban; import java.util.List; import java.util.stream.Collectors;
package com.mcbans.client.response; public class BanResponse { private String uuid = ""; private String name = "";
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // Path: src/main/java/com/mcbans/client/response/BanResponse.java import com.mcbans.domain.models.client.Ban; import java.util.List; import java.util.stream.Collectors; package com.mcbans.client.response; public class BanResponse { private String uuid = ""; private String name = "";
private List<Ban> bans;
MCBans/MCBans
src/main/java/com/mcbans/client/BanLookupClient.java
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // }
import com.mcbans.domain.models.client.Ban; import com.mcbans.utils.*; import org.bukkit.entity.Player; import java.io.IOException; import java.util.List;
package com.mcbans.client; public class BanLookupClient extends Client { public BanLookupClient(Client c) { super(c); } public BanLookupClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static BanLookupClient cast(Client client) { return new BanLookupClient(client); } public interface DataReceived{
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // Path: src/main/java/com/mcbans/client/BanLookupClient.java import com.mcbans.domain.models.client.Ban; import com.mcbans.utils.*; import org.bukkit.entity.Player; import java.io.IOException; import java.util.List; package com.mcbans.client; public class BanLookupClient extends Client { public BanLookupClient(Client c) { super(c); } public BanLookupClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static BanLookupClient cast(Client client) { return new BanLookupClient(client); } public interface DataReceived{
void received(Ban ban);
MCBans/MCBans
src/main/java/com/mcbans/client/ConnectionPool.java
// Path: src/main/java/com/mcbans/utils/TooLargeException.java // public class TooLargeException extends Exception{ // }
import com.mcbans.utils.TooLargeException; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingDeque;
package com.mcbans.client; public class ConnectionPool { private static int connections = 0; private static Queue<Client> clients = new LinkedBlockingDeque<>(); private static Map<Client, Timer> keepAliveTimer = new HashMap<>();
// Path: src/main/java/com/mcbans/utils/TooLargeException.java // public class TooLargeException extends Exception{ // } // Path: src/main/java/com/mcbans/client/ConnectionPool.java import com.mcbans.utils.TooLargeException; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; package com.mcbans.client; public class ConnectionPool { private static int connections = 0; private static Queue<Client> clients = new LinkedBlockingDeque<>(); private static Map<Client, Timer> keepAliveTimer = new HashMap<>();
public static Client getConnection(String ApiKey) throws IOException, BadApiKeyException, TooLargeException, InterruptedException {
MCBans/MCBans
src/main/java/com/mcbans/client/PlayerLookupClient.java
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Player.java // public class Player implements Serializable { // String name; // long playerId; // String uuid; // // public Player() { // } // // public Player(long playerId, String name, String uuid) { // this.name = name; // this.playerId = playerId; // this.uuid = uuid; // } // // public Player(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getPlayerId() { // return playerId; // } // // public void setPlayerId(long playerId) { // this.playerId = playerId; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // }
import com.mcbans.domain.models.client.Ban; import com.mcbans.domain.models.client.Player; import com.mcbans.utils.*; import java.io.IOException; import java.util.List;
package com.mcbans.client; public class PlayerLookupClient extends Client { public PlayerLookupClient(Client c) { super(c); } public PlayerLookupClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static PlayerLookupClient cast(Client client) { return new PlayerLookupClient(client); } public interface DataReceived{
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Player.java // public class Player implements Serializable { // String name; // long playerId; // String uuid; // // public Player() { // } // // public Player(long playerId, String name, String uuid) { // this.name = name; // this.playerId = playerId; // this.uuid = uuid; // } // // public Player(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getPlayerId() { // return playerId; // } // // public void setPlayerId(long playerId) { // this.playerId = playerId; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // } // Path: src/main/java/com/mcbans/client/PlayerLookupClient.java import com.mcbans.domain.models.client.Ban; import com.mcbans.domain.models.client.Player; import com.mcbans.utils.*; import java.io.IOException; import java.util.List; package com.mcbans.client; public class PlayerLookupClient extends Client { public PlayerLookupClient(Client c) { super(c); } public PlayerLookupClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static PlayerLookupClient cast(Client client) { return new PlayerLookupClient(client); } public interface DataReceived{
void received(Player player, List<Ban> bans, Double rep);
MCBans/MCBans
src/main/java/com/mcbans/client/PlayerLookupClient.java
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Player.java // public class Player implements Serializable { // String name; // long playerId; // String uuid; // // public Player() { // } // // public Player(long playerId, String name, String uuid) { // this.name = name; // this.playerId = playerId; // this.uuid = uuid; // } // // public Player(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getPlayerId() { // return playerId; // } // // public void setPlayerId(long playerId) { // this.playerId = playerId; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // }
import com.mcbans.domain.models.client.Ban; import com.mcbans.domain.models.client.Player; import com.mcbans.utils.*; import java.io.IOException; import java.util.List;
package com.mcbans.client; public class PlayerLookupClient extends Client { public PlayerLookupClient(Client c) { super(c); } public PlayerLookupClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static PlayerLookupClient cast(Client client) { return new PlayerLookupClient(client); } public interface DataReceived{
// Path: src/main/java/com/mcbans/domain/models/client/Ban.java // public class Ban implements Serializable { // private long id; // private String reason; // private Player admin; // private Player player; // private double reputation; // private String type; // private Long duration; // private Server server; // private Date date; // // public Ban() { // } // // public Ban(String type, String reason, double reputation, Player admin) { // this.reason = reason; // this.reputation = reputation; // this.type = type; // this.admin = admin; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public double getReputation() { // return reputation; // } // // public void setReputation(double reputation) { // this.reputation = reputation; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Long getDuration() { // return duration; // } // // public void setDuration(Long duration) { // this.duration = duration; // } // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Player getAdmin() { // return admin; // } // // public void setAdmin(Player admin) { // this.admin = admin; // } // // public Player getPlayer() { // return player; // } // // public void setPlayer(Player player) { // this.player = player; // } // } // // Path: src/main/java/com/mcbans/domain/models/client/Player.java // public class Player implements Serializable { // String name; // long playerId; // String uuid; // // public Player() { // } // // public Player(long playerId, String name, String uuid) { // this.name = name; // this.playerId = playerId; // this.uuid = uuid; // } // // public Player(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getPlayerId() { // return playerId; // } // // public void setPlayerId(long playerId) { // this.playerId = playerId; // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // } // Path: src/main/java/com/mcbans/client/PlayerLookupClient.java import com.mcbans.domain.models.client.Ban; import com.mcbans.domain.models.client.Player; import com.mcbans.utils.*; import java.io.IOException; import java.util.List; package com.mcbans.client; public class PlayerLookupClient extends Client { public PlayerLookupClient(Client c) { super(c); } public PlayerLookupClient(String apiKey) throws IOException, BadApiKeyException, TooLargeException { super(apiKey); } public static PlayerLookupClient cast(Client client) { return new PlayerLookupClient(client); } public interface DataReceived{
void received(Player player, List<Ban> bans, Double rep);
vasl-developers/vasl
src/VASL/build/module/map/ASLSniperFinder.java
// Path: src/VASL/build/module/map/boardPicker/ASLBoard.java // public static final double DEFAULT_HEX_HEIGHT = BoardArchive.GEO_HEX_HEIGHT;
import static VASL.build.module.map.boardPicker.ASLBoard.DEFAULT_HEX_HEIGHT; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.Drawable; import VASSAL.command.Command; import VASSAL.counters.*; import java.awt.*; import java.util.ArrayList;
} @Override public void setAttribute(String key, Object value) { } public void addTo(Buildable parent) { // add this component to the game if (parent instanceof Map) { this.map = (Map) parent; map.addDrawComponent(this); } } @Override public void draw(Graphics g, Map map) { if (visible) { LoadSniperPosition(); if (pointList.size() > 0) { g.setColor(Color.RED); Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); g2d.setStroke(new BasicStroke(4)); final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
// Path: src/VASL/build/module/map/boardPicker/ASLBoard.java // public static final double DEFAULT_HEX_HEIGHT = BoardArchive.GEO_HEX_HEIGHT; // Path: src/VASL/build/module/map/ASLSniperFinder.java import static VASL.build.module.map.boardPicker.ASLBoard.DEFAULT_HEX_HEIGHT; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.Drawable; import VASSAL.command.Command; import VASSAL.counters.*; import java.awt.*; import java.util.ArrayList; } @Override public void setAttribute(String key, Object value) { } public void addTo(Buildable parent) { // add this component to the game if (parent instanceof Map) { this.map = (Map) parent; map.addDrawComponent(this); } } @Override public void draw(Graphics g, Map map) { if (visible) { LoadSniperPosition(); if (pointList.size() > 0) { g.setColor(Color.RED); Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); g2d.setStroke(new BasicStroke(4)); final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final int circleSize = (int) (os_scale * map.getZoom() * DEFAULT_HEX_HEIGHT * 1.5);
vasl-developers/vasl
src/VASL/LOS/counters/Smoke.java
// Path: src/VASL/LOS/Map/Location.java // public class Location { // // // property variables // private String name; // private int baseHeight; // private Point LOSPoint; // private Point auxLOSPoint; //auxiliary LOS point for bypass locations // private Point edgeCenterPoint; // private Hex hex; // // private Terrain terrain; // private Terrain depressionTerrain; // private Location upLocation; // private Location downLocation; // // // property methods // public String getName(){return name;} // public void setName(String newName) {name = newName;} // // public Location( // String n, // int hgt, // Point LOSpt, // Point auxLOSpt, // Point edgept, // Hex hex, // Terrain terr) { // // name = n; // baseHeight = hgt; // LOSPoint = LOSpt; // auxLOSPoint = auxLOSpt; // edgeCenterPoint = edgept; // this.hex = hex; // terrain = terr; // } // // public Location(Location l) { // // // use the same points // LOSPoint = (Point) l.getLOSPoint().clone(); // auxLOSPoint = (Point) l.getAuxLOSPoint().clone(); // edgeCenterPoint = (Point) l.getEdgeCenterPoint().clone(); // // hex = l.getHex(); // // copyLocation(l); // } // // public Location(){} // // public int getBaseHeight() {return baseHeight;} // public void setBaseHeight(int newBaseHeight) {baseHeight = newBaseHeight;} // public int getAbsoluteHeight() {return baseHeight + hex.getBaseHeight();} // // public Terrain getTerrain() {return terrain;} // public void setTerrain(Terrain newTerrain) {terrain = newTerrain;} // // public Hex getHex() {return hex;} // // public Point getLOSPoint() {return LOSPoint;} // public Point getAuxLOSPoint() {return auxLOSPoint;} // public Point getEdgeCenterPoint() {return edgeCenterPoint;} // // public Terrain getDepressionTerrain(){ return depressionTerrain;} // public void setDepressionTerrain(Terrain newDepressionTerrain){ // // // removing depression terrain? // if (newDepressionTerrain == null){ // // // ensure the location base elevation is the same as the center // if(hex.getCenterLocation().isDepressionTerrain()){ // baseHeight = 1; // } // else { // baseHeight = 0; // } // } // // // adding depression terrain? // else if (depressionTerrain == null) { // // // set the location height same as center // baseHeight = 0; // // } // // depressionTerrain = newDepressionTerrain; // } // // public boolean isDepressionTerrain() { // // return (depressionTerrain != null); // } // // public boolean isCenterLocation() { // // return hex.isCenterLocation(this); // } // // public Location getUpLocation() {return upLocation;} // public void setUpLocation(Location newUpLocation) {upLocation = newUpLocation;} // // public Location getDownLocation() {return downLocation;} // public void setDownLocation(Location newDownLocation) {downLocation = newDownLocation;} // // public void copyLocation(Location l) { // // // copy the flags // baseHeight = l.getBaseHeight(); // // // copy name, terrain values // name = l.getName(); // baseHeight = l.getBaseHeight(); // terrain = l.getTerrain(); // depressionTerrain = l.getDepressionTerrain(); // } // // public boolean auxLOSPointIsCloser(int x, int y) { // // return Point.distance(x, y, LOSPoint.x, LOSPoint.y) > // Point.distance(x, y, auxLOSPoint.x, auxLOSPoint.y); // // } // // } // // Path: src/VASL/LOS/counters/Counter.java // public class Counter { // String name; // // public Counter(String name) { // this.name = name; // } // // public String getName() { return name;} // }
import VASL.LOS.Map.Location; import VASL.LOS.counters.Counter;
/* * Copyright (c) 2000-2003 by David Sullivan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASL.LOS.counters; /** * Title: Smoke.java * Copyright: Copyright (c) 2001 David Sullivan Zuericher Strasse 6 12205 Berlin Germany. All rights reserved. * @author David Sullivan * @version 1.0 */ public class Smoke extends Counter { // smoke attributes private int height; private int hindrance;
// Path: src/VASL/LOS/Map/Location.java // public class Location { // // // property variables // private String name; // private int baseHeight; // private Point LOSPoint; // private Point auxLOSPoint; //auxiliary LOS point for bypass locations // private Point edgeCenterPoint; // private Hex hex; // // private Terrain terrain; // private Terrain depressionTerrain; // private Location upLocation; // private Location downLocation; // // // property methods // public String getName(){return name;} // public void setName(String newName) {name = newName;} // // public Location( // String n, // int hgt, // Point LOSpt, // Point auxLOSpt, // Point edgept, // Hex hex, // Terrain terr) { // // name = n; // baseHeight = hgt; // LOSPoint = LOSpt; // auxLOSPoint = auxLOSpt; // edgeCenterPoint = edgept; // this.hex = hex; // terrain = terr; // } // // public Location(Location l) { // // // use the same points // LOSPoint = (Point) l.getLOSPoint().clone(); // auxLOSPoint = (Point) l.getAuxLOSPoint().clone(); // edgeCenterPoint = (Point) l.getEdgeCenterPoint().clone(); // // hex = l.getHex(); // // copyLocation(l); // } // // public Location(){} // // public int getBaseHeight() {return baseHeight;} // public void setBaseHeight(int newBaseHeight) {baseHeight = newBaseHeight;} // public int getAbsoluteHeight() {return baseHeight + hex.getBaseHeight();} // // public Terrain getTerrain() {return terrain;} // public void setTerrain(Terrain newTerrain) {terrain = newTerrain;} // // public Hex getHex() {return hex;} // // public Point getLOSPoint() {return LOSPoint;} // public Point getAuxLOSPoint() {return auxLOSPoint;} // public Point getEdgeCenterPoint() {return edgeCenterPoint;} // // public Terrain getDepressionTerrain(){ return depressionTerrain;} // public void setDepressionTerrain(Terrain newDepressionTerrain){ // // // removing depression terrain? // if (newDepressionTerrain == null){ // // // ensure the location base elevation is the same as the center // if(hex.getCenterLocation().isDepressionTerrain()){ // baseHeight = 1; // } // else { // baseHeight = 0; // } // } // // // adding depression terrain? // else if (depressionTerrain == null) { // // // set the location height same as center // baseHeight = 0; // // } // // depressionTerrain = newDepressionTerrain; // } // // public boolean isDepressionTerrain() { // // return (depressionTerrain != null); // } // // public boolean isCenterLocation() { // // return hex.isCenterLocation(this); // } // // public Location getUpLocation() {return upLocation;} // public void setUpLocation(Location newUpLocation) {upLocation = newUpLocation;} // // public Location getDownLocation() {return downLocation;} // public void setDownLocation(Location newDownLocation) {downLocation = newDownLocation;} // // public void copyLocation(Location l) { // // // copy the flags // baseHeight = l.getBaseHeight(); // // // copy name, terrain values // name = l.getName(); // baseHeight = l.getBaseHeight(); // terrain = l.getTerrain(); // depressionTerrain = l.getDepressionTerrain(); // } // // public boolean auxLOSPointIsCloser(int x, int y) { // // return Point.distance(x, y, LOSPoint.x, LOSPoint.y) > // Point.distance(x, y, auxLOSPoint.x, auxLOSPoint.y); // // } // // } // // Path: src/VASL/LOS/counters/Counter.java // public class Counter { // String name; // // public Counter(String name) { // this.name = name; // } // // public String getName() { return name;} // } // Path: src/VASL/LOS/counters/Smoke.java import VASL.LOS.Map.Location; import VASL.LOS.counters.Counter; /* * Copyright (c) 2000-2003 by David Sullivan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASL.LOS.counters; /** * Title: Smoke.java * Copyright: Copyright (c) 2001 David Sullivan Zuericher Strasse 6 12205 Berlin Germany. All rights reserved. * @author David Sullivan * @version 1.0 */ public class Smoke extends Counter { // smoke attributes private int height; private int hindrance;
private Location location;
vasl-developers/vasl
src/VASL/build/module/ASLDTODustMapShader.java
// Path: src/VASL/environment/DustLevel.java // public enum DustLevel { // NONE ("No Dust"), // LIGHT ("Light Dust (F11.71)"), // MODERATE("Moderate Dust (F11.72)"), // HEAVY("Heavy Dust (F11.73)"), // VERY_HEAVY("Very Heavy Dust (F11.731)"), // EXTREMELY_HEAVY("Extremely Heavy Dust (F11.732)"), // SPECIAL("Special Dust (Preferences->Environment)") // { // @Override // public DustLevel next() { // return NONE; // }; // }; // // private String dustLevelDescription; // // DustLevel(String s) { // dustLevelDescription = s; // } // // public String toString() { // if(values()[ordinal()] == SPECIAL){ // return (String) GameModule.getGameModule().getPrefs().getValue(ASLDTODustMapShader.SPECIAL_DUST_NAME); // } // return this.dustLevelDescription; // } // // public DustLevel next() { // return values()[ordinal() + 1]; // } // } // // Path: src/VASL/environment/DustLevel.java // public enum DustLevel { // NONE ("No Dust"), // LIGHT ("Light Dust (F11.71)"), // MODERATE("Moderate Dust (F11.72)"), // HEAVY("Heavy Dust (F11.73)"), // VERY_HEAVY("Very Heavy Dust (F11.731)"), // EXTREMELY_HEAVY("Extremely Heavy Dust (F11.732)"), // SPECIAL("Special Dust (Preferences->Environment)") // { // @Override // public DustLevel next() { // return NONE; // }; // }; // // private String dustLevelDescription; // // DustLevel(String s) { // dustLevelDescription = s; // } // // public String toString() { // if(values()[ordinal()] == SPECIAL){ // return (String) GameModule.getGameModule().getPrefs().getValue(ASLDTODustMapShader.SPECIAL_DUST_NAME); // } // return this.dustLevelDescription; // } // // public DustLevel next() { // return values()[ordinal() + 1]; // } // }
import VASL.environment.DustLevel; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.configure.StringEnumConfigurer; import VASSAL.preferences.Prefs; import javax.swing.*; import static VASL.environment.DustLevel.*;
package VASL.build.module; public class ASLDTODustMapShader extends MapShader { public final static String ENVIRONMENT = "Environment"; public final static String SPECIAL_DUST_SETTING = "UseSpecialDustSetting"; public final static String SPECIAL_DUST_NAME = "SpecialDustName"; public final static String SPECIAL_DUST_DIVIDE_BY = "SpecialDustDivideBy"; public final static String SPECIAL_DUST_ROUNDING = "SpecialDustRounding";
// Path: src/VASL/environment/DustLevel.java // public enum DustLevel { // NONE ("No Dust"), // LIGHT ("Light Dust (F11.71)"), // MODERATE("Moderate Dust (F11.72)"), // HEAVY("Heavy Dust (F11.73)"), // VERY_HEAVY("Very Heavy Dust (F11.731)"), // EXTREMELY_HEAVY("Extremely Heavy Dust (F11.732)"), // SPECIAL("Special Dust (Preferences->Environment)") // { // @Override // public DustLevel next() { // return NONE; // }; // }; // // private String dustLevelDescription; // // DustLevel(String s) { // dustLevelDescription = s; // } // // public String toString() { // if(values()[ordinal()] == SPECIAL){ // return (String) GameModule.getGameModule().getPrefs().getValue(ASLDTODustMapShader.SPECIAL_DUST_NAME); // } // return this.dustLevelDescription; // } // // public DustLevel next() { // return values()[ordinal() + 1]; // } // } // // Path: src/VASL/environment/DustLevel.java // public enum DustLevel { // NONE ("No Dust"), // LIGHT ("Light Dust (F11.71)"), // MODERATE("Moderate Dust (F11.72)"), // HEAVY("Heavy Dust (F11.73)"), // VERY_HEAVY("Very Heavy Dust (F11.731)"), // EXTREMELY_HEAVY("Extremely Heavy Dust (F11.732)"), // SPECIAL("Special Dust (Preferences->Environment)") // { // @Override // public DustLevel next() { // return NONE; // }; // }; // // private String dustLevelDescription; // // DustLevel(String s) { // dustLevelDescription = s; // } // // public String toString() { // if(values()[ordinal()] == SPECIAL){ // return (String) GameModule.getGameModule().getPrefs().getValue(ASLDTODustMapShader.SPECIAL_DUST_NAME); // } // return this.dustLevelDescription; // } // // public DustLevel next() { // return values()[ordinal() + 1]; // } // } // Path: src/VASL/build/module/ASLDTODustMapShader.java import VASL.environment.DustLevel; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.configure.StringEnumConfigurer; import VASSAL.preferences.Prefs; import javax.swing.*; import static VASL.environment.DustLevel.*; package VASL.build.module; public class ASLDTODustMapShader extends MapShader { public final static String ENVIRONMENT = "Environment"; public final static String SPECIAL_DUST_SETTING = "UseSpecialDustSetting"; public final static String SPECIAL_DUST_NAME = "SpecialDustName"; public final static String SPECIAL_DUST_DIVIDE_BY = "SpecialDustDivideBy"; public final static String SPECIAL_DUST_ROUNDING = "SpecialDustRounding";
private DustLevel dustLevel = NONE;
vasl-developers/vasl
src/VASL/counters/ASLOverlayEmbellishment.java
// Path: src/VASL/build/module/map/ASLSpacerBoards.java // public class ASLSpacerBoards { // private final static List<String> spacerBoards = Arrays.asList("bdNUL", "bdNULV"); // // public static boolean isSpacerBoard(final String boardName) { // return spacerBoards.contains(boardName); // } // }
import VASL.build.module.map.ASLSpacerBoards; import VASSAL.build.module.Map; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.widget.PieceSlot; import VASSAL.counters.Embellishment; import VASSAL.counters.GamePiece; import VASSAL.counters.Properties; import VASSAL.i18n.Resources; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Area;
.createTransformedShape(getBoardClip(obs))); area.intersect(boardArea); g.drawRect(area.getBounds().x,area.getBounds().y, area.getBounds().width, area.getBounds().height); } if (i < imagePainter.length && imagePainter[i] != null) { final Rectangle r = getCurrentImageBounds(); imagePainter[i].draw(g, x + (int)(zoom * r.x), y + (int)(zoom * r.y), zoom, obs); } if (drawUnder) { //piece.draw(g, x, y, obs, zoom); } } else { super.draw(g,x,y,obs,zoom); } } else { super.draw(g,x,y,obs,zoom); } } private Area getBoardClip(final Component obs) { Area boardClip = null; if (this.getMap() != null) { Map map = getMap(); if (map != null) { boardClip = new Area(); for (final Board b : getMap().getBoards()) { final String boardName = b.getName();
// Path: src/VASL/build/module/map/ASLSpacerBoards.java // public class ASLSpacerBoards { // private final static List<String> spacerBoards = Arrays.asList("bdNUL", "bdNULV"); // // public static boolean isSpacerBoard(final String boardName) { // return spacerBoards.contains(boardName); // } // } // Path: src/VASL/counters/ASLOverlayEmbellishment.java import VASL.build.module.map.ASLSpacerBoards; import VASSAL.build.module.Map; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.widget.PieceSlot; import VASSAL.counters.Embellishment; import VASSAL.counters.GamePiece; import VASSAL.counters.Properties; import VASSAL.i18n.Resources; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Area; .createTransformedShape(getBoardClip(obs))); area.intersect(boardArea); g.drawRect(area.getBounds().x,area.getBounds().y, area.getBounds().width, area.getBounds().height); } if (i < imagePainter.length && imagePainter[i] != null) { final Rectangle r = getCurrentImageBounds(); imagePainter[i].draw(g, x + (int)(zoom * r.x), y + (int)(zoom * r.y), zoom, obs); } if (drawUnder) { //piece.draw(g, x, y, obs, zoom); } } else { super.draw(g,x,y,obs,zoom); } } else { super.draw(g,x,y,obs,zoom); } } private Area getBoardClip(final Component obs) { Area boardClip = null; if (this.getMap() != null) { Map map = getMap(); if (map != null) { boardClip = new Area(); for (final Board b : getMap().getBoards()) { final String boardName = b.getName();
if (!ASLSpacerBoards.isSpacerBoard(boardName)) {
vasl-developers/vasl
src/VASL/build/module/ASLLVMapShader.java
// Path: src/VASL/environment/LVLevel.java // public enum LVLevel { // NONE ("No LV"), // SHADE_ONLY("LV Shading Only"), // DAWN_DUSK ("+1 LV (E3.1)"), // MIST("Mist (E3.32) +0/+1/..."), // RAIN("Rain (E3.51) +0/+1/..."), // HEAVY_RAIN("Heavy Rain (E3.51) +1/+2/..." ), // SNOW("Falling Snow (E3.71) +0/+1/..."), // HEAVY_SNOW("Heavy Falling Snow(E3.71) +1/+2/...") // { // @Override // public LVLevel next() { // return NONE; // }; // }; // // private String lvDescription; // // LVLevel(String s) { // lvDescription = s; // } // // public String toString() { // return this.lvDescription; // } // // public LVLevel next() { // return values()[ordinal() + 1]; // } // }
import VASL.environment.LVLevel; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import javax.swing.*;
package VASL.build.module; public class ASLLVMapShader extends MapShader { private final GlobalProperty globalLVLevel = new GlobalProperty();
// Path: src/VASL/environment/LVLevel.java // public enum LVLevel { // NONE ("No LV"), // SHADE_ONLY("LV Shading Only"), // DAWN_DUSK ("+1 LV (E3.1)"), // MIST("Mist (E3.32) +0/+1/..."), // RAIN("Rain (E3.51) +0/+1/..."), // HEAVY_RAIN("Heavy Rain (E3.51) +1/+2/..." ), // SNOW("Falling Snow (E3.71) +0/+1/..."), // HEAVY_SNOW("Heavy Falling Snow(E3.71) +1/+2/...") // { // @Override // public LVLevel next() { // return NONE; // }; // }; // // private String lvDescription; // // LVLevel(String s) { // lvDescription = s; // } // // public String toString() { // return this.lvDescription; // } // // public LVLevel next() { // return values()[ordinal() + 1]; // } // } // Path: src/VASL/build/module/ASLLVMapShader.java import VASL.environment.LVLevel; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import javax.swing.*; package VASL.build.module; public class ASLLVMapShader extends MapShader { private final GlobalProperty globalLVLevel = new GlobalProperty();
private LVLevel lvLevel = LVLevel.NONE;
vasl-developers/vasl
src/VASL/LOS/counters/CounterMetadataFile.java
// Path: src/VASL/LOS/counters/CounterMetadata.java // public class CounterMetadata { // // /* // name = game piece name (i.e. piece.getName()) // hindrance = # of hindrances/hex // height = height of LOS hindrance // terrain = map terrain type // level - denotes location level // position - for location denotes if pieces above/below the counter are in the location. // coverArch - covered arch of location // // */ // private String name; // private String terrain; // private int height; // private int hindrance; // private CounterType type; // private int level; // private String position; // private int coverArch; // // public static enum CounterType {SMOKE, WRECK, OBA, TERRAIN, IGNORE, BUILDING_LEVEL, CREST, ROOF, ENTRENCHMENT, CLIMB, BRIDGE, HEXSIDE} // // public CounterMetadata(String name, CounterType type) { // this.name = name; // this.type = type; // } // // /** // * @return the counter name // */ // public String getName() { // return name; // } // // /** // * @return the terrain name (for terrain-type counters) // */ // public String getTerrain() { // return terrain; // } // // /** // * @return the height (for smoke-type counters) // */ // public int getHeight() { // return height; // } // // /** // * @return the hindrance amount (for smoke counters) // */ // public int getHindrance() { // return hindrance; // } // // /** // * @return the counter type // */ // public CounterType getType() { // return type; // } // // /** // * Set the terrain (for terrain-type counters) // * @param terrain the terrain name // */ // public void setTerrain(String terrain) { // this.terrain = terrain; // } // // /** // * Set the smoke height (for smoke-type counter) // * @param height the smoke height // */ // public void setHeight(int height) { // this.height = height; // } // // /** // * Set the smoke hindrance (for smoke-type counters) // * @param hindrance the smoke hindrance level // */ // public void setHindrance(int hindrance) { // this.hindrance = hindrance; // } // // /** // * @return the location level // */ // public int getLevel() { // return level; // } // // /** // * Set the location level // * @param level the level // */ // public void setLevel(int level) { // this.level = level; // } // // /** // * @return the piece covered arch // */ // public int getCoverArch() { // return coverArch -1; // } //counters use 1-6, code uses 0-5 // // /** // * Set the piece covered arch // * @param coverArch the covered arch // */ // public void setCoverArch(int coverArch) { // this.coverArch = coverArch; // } // // /** // * @return the location position // */ // public String getPosition() { // return position; // } // // /** // * Set the location position // * @param position the covered arch // */ // public void setPosition(String position) { // this.position = position; // } // }
import java.util.LinkedHashMap; import VASL.LOS.counters.CounterMetadata; import VASSAL.build.GameModule; import VASSAL.tools.DataArchive; import VASSAL.tools.ErrorDialog; import org.apache.commons.io.IOUtils; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import java.io.IOException; import java.io.InputStream;
/* * $Id: CounterMetadataFile 3/30/14 davidsullivan1 $ * * Copyright (c) 2014 by David Sullivan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASL.LOS.counters; /** * This class provides access to the counter metadata file in the module archive */ public class CounterMetadataFile { // name of the counter metadata file in the module archive private final static String counterMetadataFileName = "CounterMetadata.xml"; // XML element and attribute names protected static final String counterMetadataElement = "counterMetadata"; protected static final String smokeCounterElement = "smoke"; protected static final String OBACounterElement = "OBA"; protected static final String terrainCounterElement = "terrain"; protected static final String wreckCounterElement = "wreck"; protected static final String ignoreCounterElement = "ignore"; protected static final String bridgeCounterElement = "bridge"; protected static final String hexsideCounterElement = "hexside"; protected static final String buildingLevelCounterElement = "buildingLevel"; protected static final String roofCounterElement = "roof"; protected static final String entrenchmentCounterElement = "entrenchment"; protected static final String crestCounterElement = "crest"; protected static final String climbCounterElement = "climb"; protected static final String locationCounterElement = "locationCounter"; protected static final String counterNameAttribute = "name"; protected static final String counterHindranceAttribute = "hindrance"; protected static final String counterHeightAttribute = "height"; protected static final String counterTerrainAttribute = "terrain"; protected static final String counterLevelAttribute = "level"; protected static final String counterPositionAttribute = "position"; protected static final String counterCoveredArchAttribute = "ca"; // constant values for the counter position attribute public static final String counterPositionAbove = "above"; public static final String getCounterPositionBelow = "below"; // List of the counter elements
// Path: src/VASL/LOS/counters/CounterMetadata.java // public class CounterMetadata { // // /* // name = game piece name (i.e. piece.getName()) // hindrance = # of hindrances/hex // height = height of LOS hindrance // terrain = map terrain type // level - denotes location level // position - for location denotes if pieces above/below the counter are in the location. // coverArch - covered arch of location // // */ // private String name; // private String terrain; // private int height; // private int hindrance; // private CounterType type; // private int level; // private String position; // private int coverArch; // // public static enum CounterType {SMOKE, WRECK, OBA, TERRAIN, IGNORE, BUILDING_LEVEL, CREST, ROOF, ENTRENCHMENT, CLIMB, BRIDGE, HEXSIDE} // // public CounterMetadata(String name, CounterType type) { // this.name = name; // this.type = type; // } // // /** // * @return the counter name // */ // public String getName() { // return name; // } // // /** // * @return the terrain name (for terrain-type counters) // */ // public String getTerrain() { // return terrain; // } // // /** // * @return the height (for smoke-type counters) // */ // public int getHeight() { // return height; // } // // /** // * @return the hindrance amount (for smoke counters) // */ // public int getHindrance() { // return hindrance; // } // // /** // * @return the counter type // */ // public CounterType getType() { // return type; // } // // /** // * Set the terrain (for terrain-type counters) // * @param terrain the terrain name // */ // public void setTerrain(String terrain) { // this.terrain = terrain; // } // // /** // * Set the smoke height (for smoke-type counter) // * @param height the smoke height // */ // public void setHeight(int height) { // this.height = height; // } // // /** // * Set the smoke hindrance (for smoke-type counters) // * @param hindrance the smoke hindrance level // */ // public void setHindrance(int hindrance) { // this.hindrance = hindrance; // } // // /** // * @return the location level // */ // public int getLevel() { // return level; // } // // /** // * Set the location level // * @param level the level // */ // public void setLevel(int level) { // this.level = level; // } // // /** // * @return the piece covered arch // */ // public int getCoverArch() { // return coverArch -1; // } //counters use 1-6, code uses 0-5 // // /** // * Set the piece covered arch // * @param coverArch the covered arch // */ // public void setCoverArch(int coverArch) { // this.coverArch = coverArch; // } // // /** // * @return the location position // */ // public String getPosition() { // return position; // } // // /** // * Set the location position // * @param position the covered arch // */ // public void setPosition(String position) { // this.position = position; // } // } // Path: src/VASL/LOS/counters/CounterMetadataFile.java import java.util.LinkedHashMap; import VASL.LOS.counters.CounterMetadata; import VASSAL.build.GameModule; import VASSAL.tools.DataArchive; import VASSAL.tools.ErrorDialog; import org.apache.commons.io.IOUtils; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import java.io.IOException; import java.io.InputStream; /* * $Id: CounterMetadataFile 3/30/14 davidsullivan1 $ * * Copyright (c) 2014 by David Sullivan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASL.LOS.counters; /** * This class provides access to the counter metadata file in the module archive */ public class CounterMetadataFile { // name of the counter metadata file in the module archive private final static String counterMetadataFileName = "CounterMetadata.xml"; // XML element and attribute names protected static final String counterMetadataElement = "counterMetadata"; protected static final String smokeCounterElement = "smoke"; protected static final String OBACounterElement = "OBA"; protected static final String terrainCounterElement = "terrain"; protected static final String wreckCounterElement = "wreck"; protected static final String ignoreCounterElement = "ignore"; protected static final String bridgeCounterElement = "bridge"; protected static final String hexsideCounterElement = "hexside"; protected static final String buildingLevelCounterElement = "buildingLevel"; protected static final String roofCounterElement = "roof"; protected static final String entrenchmentCounterElement = "entrenchment"; protected static final String crestCounterElement = "crest"; protected static final String climbCounterElement = "climb"; protected static final String locationCounterElement = "locationCounter"; protected static final String counterNameAttribute = "name"; protected static final String counterHindranceAttribute = "hindrance"; protected static final String counterHeightAttribute = "height"; protected static final String counterTerrainAttribute = "terrain"; protected static final String counterLevelAttribute = "level"; protected static final String counterPositionAttribute = "position"; protected static final String counterCoveredArchAttribute = "ca"; // constant values for the counter position attribute public static final String counterPositionAbove = "above"; public static final String getCounterPositionBelow = "below"; // List of the counter elements
protected LinkedHashMap<String, CounterMetadata> metadataElements = new LinkedHashMap<String, CounterMetadata>(30);
vasl-developers/vasl
src/VASL/build/module/map/ASLPieceFinder.java
// Path: src/VASL/build/module/map/boardPicker/ASLBoard.java // public static final double DEFAULT_HEX_HEIGHT = BoardArchive.GEO_HEX_HEIGHT;
import static VASL.build.module.map.boardPicker.ASLBoard.DEFAULT_HEX_HEIGHT; import static VASSAL.build.GameModule.getGameModule; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.Drawable; import VASSAL.command.Command; import VASSAL.command.CommandEncoder; import VASSAL.tools.swing.SwingUtils; import VASSAL.configure.BooleanConfigurer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener;
map.addLocalMouseListener(this); timer = new Timer (CIRCLE_DURATION, this); final BooleanConfigurer Highlightcenter = new BooleanConfigurer("HighlightCentered", "Opponent's Highlight Centered on Your Map", true); getGameModule().getPrefs().addOption(preferenceTabName, Highlightcenter); final BooleanConfigurer Highlightcircle = new BooleanConfigurer("HighlightShowCircle", "Highlight Shows Red Circle on Map", true); getGameModule().getPrefs().addOption(preferenceTabName, Highlightcircle); } } public void startAnimation(boolean isLocal) { // do not adjust the view of the player who initiated the command if (!isLocal && isHighlightCentered()) { map.centerAt(clickPoint); } active = true; timer.restart(); map.getView().repaint(); } @Override public void draw(Graphics g, Map map) { if (!active || clickPoint == null) { return; } final Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
// Path: src/VASL/build/module/map/boardPicker/ASLBoard.java // public static final double DEFAULT_HEX_HEIGHT = BoardArchive.GEO_HEX_HEIGHT; // Path: src/VASL/build/module/map/ASLPieceFinder.java import static VASL.build.module.map.boardPicker.ASLBoard.DEFAULT_HEX_HEIGHT; import static VASSAL.build.GameModule.getGameModule; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.Drawable; import VASSAL.command.Command; import VASSAL.command.CommandEncoder; import VASSAL.tools.swing.SwingUtils; import VASSAL.configure.BooleanConfigurer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; map.addLocalMouseListener(this); timer = new Timer (CIRCLE_DURATION, this); final BooleanConfigurer Highlightcenter = new BooleanConfigurer("HighlightCentered", "Opponent's Highlight Centered on Your Map", true); getGameModule().getPrefs().addOption(preferenceTabName, Highlightcenter); final BooleanConfigurer Highlightcircle = new BooleanConfigurer("HighlightShowCircle", "Highlight Shows Red Circle on Map", true); getGameModule().getPrefs().addOption(preferenceTabName, Highlightcircle); } } public void startAnimation(boolean isLocal) { // do not adjust the view of the player who initiated the command if (!isLocal && isHighlightCentered()) { map.centerAt(clickPoint); } active = true; timer.restart(); map.getView().repaint(); } @Override public void draw(Graphics g, Map map) { if (!active || clickPoint == null) { return; } final Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final int diameter = (int)(map.getZoom() * os_scale * DEFAULT_HEX_HEIGHT * 2);
vasl-developers/vasl
src/VASL/build/module/map/ASLBrokenFinder.java
// Path: src/VASL/build/module/map/boardPicker/ASLBoard.java // public static final double DEFAULT_HEX_HEIGHT = BoardArchive.GEO_HEX_HEIGHT;
import VASSAL.counters.GamePiece; import VASSAL.counters.PieceIterator; import java.awt.*; import java.util.ArrayList; import static VASL.build.module.map.boardPicker.ASLBoard.DEFAULT_HEX_HEIGHT; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.Drawable; import VASSAL.command.Command; import VASSAL.configure.PropertyExpression; import VASSAL.counters.BasicPiece; import VASSAL.counters.Decorator;
} @Override public void setAttribute(String key, Object value) { } @Override public void addTo(Buildable parent) { // add this component to the game and register a mouse listener if (parent instanceof Map) { this.m_objMap = (Map) parent; m_objMap.addDrawComponent(this); m_piecePropertiesFilter.setExpression("InvisibleToOthers != true && BRK_Active = true || PieceName = DM || PieceName = Disrupt"); } } @Override public void draw(Graphics g, Map map) { if (m_bVisible) { LoadBrokenPiecesPosition(); if (mar_objPointList.size() > 0) { final Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
// Path: src/VASL/build/module/map/boardPicker/ASLBoard.java // public static final double DEFAULT_HEX_HEIGHT = BoardArchive.GEO_HEX_HEIGHT; // Path: src/VASL/build/module/map/ASLBrokenFinder.java import VASSAL.counters.GamePiece; import VASSAL.counters.PieceIterator; import java.awt.*; import java.util.ArrayList; import static VASL.build.module.map.boardPicker.ASLBoard.DEFAULT_HEX_HEIGHT; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.Drawable; import VASSAL.command.Command; import VASSAL.configure.PropertyExpression; import VASSAL.counters.BasicPiece; import VASSAL.counters.Decorator; } @Override public void setAttribute(String key, Object value) { } @Override public void addTo(Buildable parent) { // add this component to the game and register a mouse listener if (parent instanceof Map) { this.m_objMap = (Map) parent; m_objMap.addDrawComponent(this); m_piecePropertiesFilter.setExpression("InvisibleToOthers != true && BRK_Active = true || PieceName = DM || PieceName = Disrupt"); } } @Override public void draw(Graphics g, Map map) { if (m_bVisible) { LoadBrokenPiecesPosition(); if (mar_objPointList.size() > 0) { final Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final int diam = (int)(os_scale * map.getZoom() * DEFAULT_HEX_HEIGHT);
vasl-developers/vasl
src/VASL/build/module/ASLSunBlindnessMapShader.java
// Path: src/VASL/environment/SunBlindnessLevel.java // public enum SunBlindnessLevel { // NONE ("No Sun Blindness"), // EARLY_MORNING_SUN_BLINDNESS("Early Morning Sun Blindness (F11.611) +2 => E"), // LATE_AFTERNOON_SUN_BLINDNESS ("Late Afternoon Sun Blindness (F11.612) +2 => W") // { // @Override // public SunBlindnessLevel next() { // return NONE; // } // }; // // private String sunBlindnessDescription; // // SunBlindnessLevel(String s) { // sunBlindnessDescription = s; // } // // public String toString() { // return this.sunBlindnessDescription; // } // // public SunBlindnessLevel next() { // return values()[ordinal() + 1]; // } // }
import VASL.environment.SunBlindnessLevel; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import javax.swing.*; import static VASL.environment.SunBlindnessLevel.NONE;
package VASL.build.module; public class ASLSunBlindnessMapShader extends MapShader { private final GlobalProperty globalSunBlindnessLevel = new GlobalProperty();
// Path: src/VASL/environment/SunBlindnessLevel.java // public enum SunBlindnessLevel { // NONE ("No Sun Blindness"), // EARLY_MORNING_SUN_BLINDNESS("Early Morning Sun Blindness (F11.611) +2 => E"), // LATE_AFTERNOON_SUN_BLINDNESS ("Late Afternoon Sun Blindness (F11.612) +2 => W") // { // @Override // public SunBlindnessLevel next() { // return NONE; // } // }; // // private String sunBlindnessDescription; // // SunBlindnessLevel(String s) { // sunBlindnessDescription = s; // } // // public String toString() { // return this.sunBlindnessDescription; // } // // public SunBlindnessLevel next() { // return values()[ordinal() + 1]; // } // } // Path: src/VASL/build/module/ASLSunBlindnessMapShader.java import VASL.environment.SunBlindnessLevel; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import javax.swing.*; import static VASL.environment.SunBlindnessLevel.NONE; package VASL.build.module; public class ASLSunBlindnessMapShader extends MapShader { private final GlobalProperty globalSunBlindnessLevel = new GlobalProperty();
private SunBlindnessLevel sunBlindnessLevel = NONE;
vasl-developers/vasl
src/VASL/build/module/ASLHeatHazeMapShader.java
// Path: src/VASL/environment/HeatHazeLevel.java // public enum HeatHazeLevel { // NONE ("No Heat Haze"), // HEAT_HAZE("Heat Haze (F11.62)"), // INTENSE_HEAT_HAZE("Intense Heat Haze (F11.621)") // { // @Override // public HeatHazeLevel next() { // return NONE; // }; // }; // // private String heatHazeDescription; // // HeatHazeLevel(String s) { // heatHazeDescription = s; // } // // public String toString() { // return this.heatHazeDescription; // } // // public HeatHazeLevel next() { // return values()[ordinal() + 1]; // } // }
import VASL.environment.HeatHazeLevel; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import javax.swing.*; import static VASL.environment.HeatHazeLevel.NONE;
package VASL.build.module; public class ASLHeatHazeMapShader extends MapShader { private final GlobalProperty globalHeatHazeLevel = new GlobalProperty();
// Path: src/VASL/environment/HeatHazeLevel.java // public enum HeatHazeLevel { // NONE ("No Heat Haze"), // HEAT_HAZE("Heat Haze (F11.62)"), // INTENSE_HEAT_HAZE("Intense Heat Haze (F11.621)") // { // @Override // public HeatHazeLevel next() { // return NONE; // }; // }; // // private String heatHazeDescription; // // HeatHazeLevel(String s) { // heatHazeDescription = s; // } // // public String toString() { // return this.heatHazeDescription; // } // // public HeatHazeLevel next() { // return values()[ordinal() + 1]; // } // } // Path: src/VASL/build/module/ASLHeatHazeMapShader.java import VASL.environment.HeatHazeLevel; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.properties.GlobalProperty; import javax.swing.*; import static VASL.environment.HeatHazeLevel.NONE; package VASL.build.module; public class ASLHeatHazeMapShader extends MapShader { private final GlobalProperty globalHeatHazeLevel = new GlobalProperty();
private HeatHazeLevel heatHazeLevel = NONE;
vasl-developers/vasl
src/VASL/counters/ASLOverlayCounter.java
// Path: src/VASL/build/module/map/ASLSpacerBoards.java // public class ASLSpacerBoards { // private final static List<String> spacerBoards = Arrays.asList("bdNUL", "bdNULV"); // // public static boolean isSpacerBoard(final String boardName) { // return spacerBoards.contains(boardName); // } // }
import VASL.build.module.map.ASLSpacerBoards; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.command.Command; import VASSAL.counters.*; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.imageop.ScaledImagePainter; import javax.swing.*; import java.awt.*; import java.awt.geom.Area;
imageBounds = getInner().boundingBox(); } imageBounds = imageBounds.intersection(boardArea.getBounds()); scaledImagePainter.draw(g, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), zoom, obs); } @Override public Rectangle boundingBox() { return getInner().boundingBox(); } @Override public Shape getShape() { return getInner().getShape(); } @Override public String getName() { return getInner().getName(); } private Area getBoardClip(final Component obs) { if (this.getMap() != null) { Map map = getMap(); if (map != null) { if (boardClip == null) { boardClip = new Area(); for (final Board b : getMap().getBoards()) { final String boardName = b.getName();
// Path: src/VASL/build/module/map/ASLSpacerBoards.java // public class ASLSpacerBoards { // private final static List<String> spacerBoards = Arrays.asList("bdNUL", "bdNULV"); // // public static boolean isSpacerBoard(final String boardName) { // return spacerBoards.contains(boardName); // } // } // Path: src/VASL/counters/ASLOverlayCounter.java import VASL.build.module.map.ASLSpacerBoards; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.command.Command; import VASSAL.counters.*; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.imageop.ScaledImagePainter; import javax.swing.*; import java.awt.*; import java.awt.geom.Area; imageBounds = getInner().boundingBox(); } imageBounds = imageBounds.intersection(boardArea.getBounds()); scaledImagePainter.draw(g, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), zoom, obs); } @Override public Rectangle boundingBox() { return getInner().boundingBox(); } @Override public Shape getShape() { return getInner().getShape(); } @Override public String getName() { return getInner().getName(); } private Area getBoardClip(final Component obs) { if (this.getMap() != null) { Map map = getMap(); if (map != null) { if (boardClip == null) { boardClip = new Area(); for (final Board b : getMap().getBoards()) { final String boardName = b.getName();
if (!ASLSpacerBoards.isSpacerBoard(boardName)) {
vasl-developers/vasl
src/VASL/LOS/Map/LOSResult.java
// Path: src/VASL/LOS/counters/OBA.java // public class OBA extends Counter { // // private Hex hex; // private int blastHeight = 2; // private int blastAreaRadius = 1; // // /** // * Create an OBA counter // * @param name the counter name // * @param hex the hex location of the counter // */ // public OBA(String name, Hex hex){ // super(name); // this.hex = hex; // } // // /** // * @return the hex location of the OBA counter // */ // public Hex getHex(){ // return hex; // } // // /** // * @return the blast height of the OBA // */ // public int getBlastHeight(){ // return blastHeight; // } // // /** // * @return the max range of the blast area from the counter // */ // public int getBlastAreaRadius(){ // return blastAreaRadius; // } // }
import VASL.LOS.counters.OBA; import java.awt.*; import java.util.HashMap; import java.util.HashSet;
/* * Copyright (c) 2000-2003 by David Sullivan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASL.LOS.Map; /** * Title: LOSResult.java * Copyright: Copyright (c) 2001 David Sullivan Zuericher Strasse 6 12205 Berlin Germany. All rights reserved. * @author David Sullivan * @version 1.0 */ public class LOSResult { // some useful constants public static final int UNKNOWN = -1; // private variables protected Location sourceLocation; private Location targetLocation; private boolean blocked; private Point blockedAtPoint; protected Point firstHindranceAt; private int range; protected int sourceExitHexspine = UNKNOWN; private int targetEnterHexspine = UNKNOWN; private String reason = ""; private boolean continuousSlope; protected boolean LOSis60Degree; private boolean LOSisHorizontal; // the <Integer> is the range to the hindrance hex protected HashMap<Integer, Integer> mapHindrances = new HashMap<Integer, Integer>(); // <Integer, Integer> = <range, hindrance> private HashMap<Integer, Integer> smokeHindrances = new HashMap<Integer, Integer>(); private HashMap<Integer, Integer> vehicleHindrances = new HashMap<Integer, Integer>();
// Path: src/VASL/LOS/counters/OBA.java // public class OBA extends Counter { // // private Hex hex; // private int blastHeight = 2; // private int blastAreaRadius = 1; // // /** // * Create an OBA counter // * @param name the counter name // * @param hex the hex location of the counter // */ // public OBA(String name, Hex hex){ // super(name); // this.hex = hex; // } // // /** // * @return the hex location of the OBA counter // */ // public Hex getHex(){ // return hex; // } // // /** // * @return the blast height of the OBA // */ // public int getBlastHeight(){ // return blastHeight; // } // // /** // * @return the max range of the blast area from the counter // */ // public int getBlastAreaRadius(){ // return blastAreaRadius; // } // } // Path: src/VASL/LOS/Map/LOSResult.java import VASL.LOS.counters.OBA; import java.awt.*; import java.util.HashMap; import java.util.HashSet; /* * Copyright (c) 2000-2003 by David Sullivan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASL.LOS.Map; /** * Title: LOSResult.java * Copyright: Copyright (c) 2001 David Sullivan Zuericher Strasse 6 12205 Berlin Germany. All rights reserved. * @author David Sullivan * @version 1.0 */ public class LOSResult { // some useful constants public static final int UNKNOWN = -1; // private variables protected Location sourceLocation; private Location targetLocation; private boolean blocked; private Point blockedAtPoint; protected Point firstHindranceAt; private int range; protected int sourceExitHexspine = UNKNOWN; private int targetEnterHexspine = UNKNOWN; private String reason = ""; private boolean continuousSlope; protected boolean LOSis60Degree; private boolean LOSisHorizontal; // the <Integer> is the range to the hindrance hex protected HashMap<Integer, Integer> mapHindrances = new HashMap<Integer, Integer>(); // <Integer, Integer> = <range, hindrance> private HashMap<Integer, Integer> smokeHindrances = new HashMap<Integer, Integer>(); private HashMap<Integer, Integer> vehicleHindrances = new HashMap<Integer, Integer>();
private HashSet<OBA> obaHindrances = new HashSet<OBA>();
vasl-developers/vasl
src/VASL/environment/DustLevel.java
// Path: src/VASL/build/module/ASLDTODustMapShader.java // public class ASLDTODustMapShader extends MapShader { // public final static String ENVIRONMENT = "Environment"; // public final static String SPECIAL_DUST_SETTING = "UseSpecialDustSetting"; // public final static String SPECIAL_DUST_NAME = "SpecialDustName"; // public final static String SPECIAL_DUST_DIVIDE_BY = "SpecialDustDivideBy"; // public final static String SPECIAL_DUST_ROUNDING = "SpecialDustRounding"; // // private DustLevel dustLevel = NONE; // private BooleanConfigurer useSpecialDustSetting; // private final GlobalProperty globalDustLevel = new GlobalProperty(); // // public ASLDTODustMapShader() { // super(); // globalDustLevel.setPropertyName("dust_level"); // globalDustLevel.setAttribute("initialValue", dustLevel.name()); // GameModule gm = GameModule.getGameModule(); // gm.addMutableProperty("dust_level", globalDustLevel); // } // // @Override // public void addTo(Buildable b) { // super.addTo(b); // Prefs modulePreferences = GameModule.getGameModule().getPrefs(); // // if(modulePreferences.getValue(SPECIAL_DUST_SETTING) == null) { // useSpecialDustSetting = new BooleanConfigurer(SPECIAL_DUST_SETTING, "Use Special Dust Setting", false); // modulePreferences.addOption(ENVIRONMENT, useSpecialDustSetting); // useSpecialDustSetting.addPropertyChangeListener( listener -> { // boolean specialDust = (Boolean)listener.getNewValue(); // if( specialDust) { // dustLevel = SPECIAL; // } // setShadingVisibility(setDustAndOpacity()); // }); // } // if(modulePreferences.getValue(SPECIAL_DUST_NAME) == null) { // StringConfigurer dustName = new StringConfigurer(SPECIAL_DUST_NAME, "Dust Type Name (For chatter)", "Special Dust"); // modulePreferences.addOption(ENVIRONMENT, dustName); // } // if(modulePreferences.getValue(SPECIAL_DUST_DIVIDE_BY) == null) { // String [] divideValues = {"1","2","3","4","5","6"}; // StringEnumConfigurer divideBy = new StringEnumConfigurer(SPECIAL_DUST_DIVIDE_BY, "Divide roll by", divideValues); // modulePreferences.addOption(ENVIRONMENT, divideBy); // } // if(modulePreferences.getValue(SPECIAL_DUST_ROUNDING) == null) { // String [] roundingValues = {"up","down"}; // StringEnumConfigurer rounding = new StringEnumConfigurer(SPECIAL_DUST_ROUNDING, "Fractions rounded", roundingValues); // modulePreferences.addOption(ENVIRONMENT, rounding); // } // useSpecialDustSetting.fireUpdate(); // } // // // @Override // protected void toggleShading() { // Object[] possibilities = DustLevel.values(); // DustLevel tempDustLevel = (DustLevel) JOptionPane.showInputDialog( // getLaunchButton().getParent(), // "Select Dust Type:", // "Dust Type", // JOptionPane.PLAIN_MESSAGE, // getLaunchButton().getIcon(), // possibilities, // dustLevel.toString()); // if(tempDustLevel != null) { // dustLevel = tempDustLevel; // } // if(GameModule.getGameModule().getChatter()!= null) { // GameModule.getGameModule().getChatter().send(dustLevel.toString() + " is in effect."); // } // if(dustLevel == SPECIAL) { // useSpecialDustSetting.setValue(true); // } else { // useSpecialDustSetting.setValue(false); // } // // this.setShadingVisibility(setDustAndOpacity()); // } // // private boolean setDustAndOpacity() { // switch (dustLevel) { // case NONE: // opacity = 0; // break; // case LIGHT: // opacity = 5; // break; // case MODERATE: // opacity = 10; // break; // case HEAVY: // opacity = 15; // break; // case VERY_HEAVY: // opacity = 20; // break; // case EXTREMELY_HEAVY: // opacity = 25; // break; // case SPECIAL: { // opacity = 10; // break; // } // } // globalDustLevel.setAttribute("initialValue", dustLevel.name()); // buildComposite(); // return dustLevel != NONE; // } // // }
import VASL.build.module.ASLDTODustMapShader; import VASSAL.build.GameModule;
package VASL.environment; public enum DustLevel { NONE ("No Dust"), LIGHT ("Light Dust (F11.71)"), MODERATE("Moderate Dust (F11.72)"), HEAVY("Heavy Dust (F11.73)"), VERY_HEAVY("Very Heavy Dust (F11.731)"), EXTREMELY_HEAVY("Extremely Heavy Dust (F11.732)"), SPECIAL("Special Dust (Preferences->Environment)") { @Override public DustLevel next() { return NONE; }; }; private String dustLevelDescription; DustLevel(String s) { dustLevelDescription = s; } public String toString() { if(values()[ordinal()] == SPECIAL){
// Path: src/VASL/build/module/ASLDTODustMapShader.java // public class ASLDTODustMapShader extends MapShader { // public final static String ENVIRONMENT = "Environment"; // public final static String SPECIAL_DUST_SETTING = "UseSpecialDustSetting"; // public final static String SPECIAL_DUST_NAME = "SpecialDustName"; // public final static String SPECIAL_DUST_DIVIDE_BY = "SpecialDustDivideBy"; // public final static String SPECIAL_DUST_ROUNDING = "SpecialDustRounding"; // // private DustLevel dustLevel = NONE; // private BooleanConfigurer useSpecialDustSetting; // private final GlobalProperty globalDustLevel = new GlobalProperty(); // // public ASLDTODustMapShader() { // super(); // globalDustLevel.setPropertyName("dust_level"); // globalDustLevel.setAttribute("initialValue", dustLevel.name()); // GameModule gm = GameModule.getGameModule(); // gm.addMutableProperty("dust_level", globalDustLevel); // } // // @Override // public void addTo(Buildable b) { // super.addTo(b); // Prefs modulePreferences = GameModule.getGameModule().getPrefs(); // // if(modulePreferences.getValue(SPECIAL_DUST_SETTING) == null) { // useSpecialDustSetting = new BooleanConfigurer(SPECIAL_DUST_SETTING, "Use Special Dust Setting", false); // modulePreferences.addOption(ENVIRONMENT, useSpecialDustSetting); // useSpecialDustSetting.addPropertyChangeListener( listener -> { // boolean specialDust = (Boolean)listener.getNewValue(); // if( specialDust) { // dustLevel = SPECIAL; // } // setShadingVisibility(setDustAndOpacity()); // }); // } // if(modulePreferences.getValue(SPECIAL_DUST_NAME) == null) { // StringConfigurer dustName = new StringConfigurer(SPECIAL_DUST_NAME, "Dust Type Name (For chatter)", "Special Dust"); // modulePreferences.addOption(ENVIRONMENT, dustName); // } // if(modulePreferences.getValue(SPECIAL_DUST_DIVIDE_BY) == null) { // String [] divideValues = {"1","2","3","4","5","6"}; // StringEnumConfigurer divideBy = new StringEnumConfigurer(SPECIAL_DUST_DIVIDE_BY, "Divide roll by", divideValues); // modulePreferences.addOption(ENVIRONMENT, divideBy); // } // if(modulePreferences.getValue(SPECIAL_DUST_ROUNDING) == null) { // String [] roundingValues = {"up","down"}; // StringEnumConfigurer rounding = new StringEnumConfigurer(SPECIAL_DUST_ROUNDING, "Fractions rounded", roundingValues); // modulePreferences.addOption(ENVIRONMENT, rounding); // } // useSpecialDustSetting.fireUpdate(); // } // // // @Override // protected void toggleShading() { // Object[] possibilities = DustLevel.values(); // DustLevel tempDustLevel = (DustLevel) JOptionPane.showInputDialog( // getLaunchButton().getParent(), // "Select Dust Type:", // "Dust Type", // JOptionPane.PLAIN_MESSAGE, // getLaunchButton().getIcon(), // possibilities, // dustLevel.toString()); // if(tempDustLevel != null) { // dustLevel = tempDustLevel; // } // if(GameModule.getGameModule().getChatter()!= null) { // GameModule.getGameModule().getChatter().send(dustLevel.toString() + " is in effect."); // } // if(dustLevel == SPECIAL) { // useSpecialDustSetting.setValue(true); // } else { // useSpecialDustSetting.setValue(false); // } // // this.setShadingVisibility(setDustAndOpacity()); // } // // private boolean setDustAndOpacity() { // switch (dustLevel) { // case NONE: // opacity = 0; // break; // case LIGHT: // opacity = 5; // break; // case MODERATE: // opacity = 10; // break; // case HEAVY: // opacity = 15; // break; // case VERY_HEAVY: // opacity = 20; // break; // case EXTREMELY_HEAVY: // opacity = 25; // break; // case SPECIAL: { // opacity = 10; // break; // } // } // globalDustLevel.setAttribute("initialValue", dustLevel.name()); // buildComposite(); // return dustLevel != NONE; // } // // } // Path: src/VASL/environment/DustLevel.java import VASL.build.module.ASLDTODustMapShader; import VASSAL.build.GameModule; package VASL.environment; public enum DustLevel { NONE ("No Dust"), LIGHT ("Light Dust (F11.71)"), MODERATE("Moderate Dust (F11.72)"), HEAVY("Heavy Dust (F11.73)"), VERY_HEAVY("Very Heavy Dust (F11.731)"), EXTREMELY_HEAVY("Extremely Heavy Dust (F11.732)"), SPECIAL("Special Dust (Preferences->Environment)") { @Override public DustLevel next() { return NONE; }; }; private String dustLevelDescription; DustLevel(String s) { dustLevelDescription = s; } public String toString() { if(values()[ordinal()] == SPECIAL){
return (String) GameModule.getGameModule().getPrefs().getValue(ASLDTODustMapShader.SPECIAL_DUST_NAME);
loomchild/segment
segment/src/test/java/net/loomchild/segment/srx/AbstractSrxTextIteratorTest.java
// Path: segment/src/main/java/net/loomchild/segment/TextIterator.java // public interface TextIterator extends Iterator<String> { // // /** // * @return next segment in text, or null if end of text has been // * reached. // */ // public String next(); // // /** // * @return true if there are more segments // */ // public boolean hasNext(); // // /** // * Unsupported operation. // * // * @throws UnsupportedOperationException // */ // public void remove(); // // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.loomchild.segment.TextIterator; import org.junit.Test;
LanguageRule languageRule = new LanguageRule(""); languageRule.addRule(new Rule(false, "\\sU\\.K\\.", "\\s")); languageRule.addRule(new Rule(false, "Mr\\.", "\\s")); languageRule.addRule(new Rule(true, "[\\.\\?!]+", "\\s")); SrxDocument document = new SrxDocument(); document.addLanguageMap(".*", languageRule); return document; } /** * Tests situation described in SRX specification as an example. * The text is slightly shorter to decrease buffer size for tests. */ @Test public void testSpecificationExample() { performTest(SPECIFICATION_EXAMPLE_RESULT, SPECIFICATION_EXAMPLE_DOCUMENT); } /** * Create text iterator. This method needs to be implemented by inheriting. * @param document SRX document * @param languageCode language code of text * @param text text to segment * @return newly created text iterator */
// Path: segment/src/main/java/net/loomchild/segment/TextIterator.java // public interface TextIterator extends Iterator<String> { // // /** // * @return next segment in text, or null if end of text has been // * reached. // */ // public String next(); // // /** // * @return true if there are more segments // */ // public boolean hasNext(); // // /** // * Unsupported operation. // * // * @throws UnsupportedOperationException // */ // public void remove(); // // } // Path: segment/src/test/java/net/loomchild/segment/srx/AbstractSrxTextIteratorTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.loomchild.segment.TextIterator; import org.junit.Test; LanguageRule languageRule = new LanguageRule(""); languageRule.addRule(new Rule(false, "\\sU\\.K\\.", "\\s")); languageRule.addRule(new Rule(false, "Mr\\.", "\\s")); languageRule.addRule(new Rule(true, "[\\.\\?!]+", "\\s")); SrxDocument document = new SrxDocument(); document.addLanguageMap(".*", languageRule); return document; } /** * Tests situation described in SRX specification as an example. * The text is slightly shorter to decrease buffer size for tests. */ @Test public void testSpecificationExample() { performTest(SPECIFICATION_EXAMPLE_RESULT, SPECIFICATION_EXAMPLE_DOCUMENT); } /** * Create text iterator. This method needs to be implemented by inheriting. * @param document SRX document * @param languageCode language code of text * @param text text to segment * @return newly created text iterator */
protected abstract TextIterator getTextIterator(SrxDocument document,