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 |
|---|---|---|---|---|---|---|
spinnaker/fiat | fiat-web/src/main/java/com/netflix/spinnaker/fiat/controllers/ControllerSupport.java | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/config/UnrestrictedResourceConfig.java
// @Configuration
// public class UnrestrictedResourceConfig {
//
// public static String UNRESTRICTED_USERNAME = "__unrestricted_user__";
//
// @Bean
// @ConditionalOnExpression("${fiat.write-mode.enabled:true}")
// String addUnrestrictedUser(PermissionsRepository permissionsRepository) {
// if (!permissionsRepository.get(UNRESTRICTED_USERNAME).isPresent()) {
// permissionsRepository.put(new UserPermission().setId(UNRESTRICTED_USERNAME));
// }
// return UNRESTRICTED_USERNAME;
// }
// }
| import com.netflix.spinnaker.fiat.config.UnrestrictedResourceConfig;
import lombok.extern.slf4j.Slf4j; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.controllers;
@Slf4j
public class ControllerSupport {
static final String ANONYMOUS_USER = "anonymous";
static String convert(String in) {
if (ANONYMOUS_USER.equalsIgnoreCase(in)) { | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/config/UnrestrictedResourceConfig.java
// @Configuration
// public class UnrestrictedResourceConfig {
//
// public static String UNRESTRICTED_USERNAME = "__unrestricted_user__";
//
// @Bean
// @ConditionalOnExpression("${fiat.write-mode.enabled:true}")
// String addUnrestrictedUser(PermissionsRepository permissionsRepository) {
// if (!permissionsRepository.get(UNRESTRICTED_USERNAME).isPresent()) {
// permissionsRepository.put(new UserPermission().setId(UNRESTRICTED_USERNAME));
// }
// return UNRESTRICTED_USERNAME;
// }
// }
// Path: fiat-web/src/main/java/com/netflix/spinnaker/fiat/controllers/ControllerSupport.java
import com.netflix.spinnaker.fiat.config.UnrestrictedResourceConfig;
import lombok.extern.slf4j.Slf4j;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.controllers;
@Slf4j
public class ControllerSupport {
static final String ANONYMOUS_USER = "anonymous";
static String convert(String in) {
if (ANONYMOUS_USER.equalsIgnoreCase(in)) { | return UnrestrictedResourceConfig.UNRESTRICTED_USERNAME; |
spinnaker/fiat | fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
| import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component; | /*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.model.resources;
@Component
@Data
@EqualsAndHashCode(callSuper = false)
public class BuildService implements Resource.AccessControlled, Viewable {
private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
private String name;
private Permissions permissions = Permissions.EMPTY;
@Override
public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
return new View(this, userRoles, isAdmin);
}
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public static class View extends Viewable.BaseView implements Authorizable {
private String name; | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.model.resources;
@Component
@Data
@EqualsAndHashCode(callSuper = false)
public class BuildService implements Resource.AccessControlled, Viewable {
private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
private String name;
private Permissions permissions = Permissions.EMPTY;
@Override
public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
return new View(this, userRoles, isAdmin);
}
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public static class View extends Viewable.BaseView implements Authorizable {
private String name; | Set<Authorization> authorizations; |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorApi.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.BuildService;
import java.util.List;
import retrofit.http.GET; | /*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers.internal;
public interface IgorApi {
@GET("/buildServices") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorApi.java
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import java.util.List;
import retrofit.http.GET;
/*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers.internal;
public interface IgorApi {
@GET("/buildServices") | List<BuildService> getBuildMasters(); |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/BaseServiceAccountResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
| import com.netflix.spinnaker.fiat.config.FiatRoleConfig;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import lombok.NonNull; | package com.netflix.spinnaker.fiat.providers;
public abstract class BaseServiceAccountResourceProvider
extends BaseResourceProvider<ServiceAccount> {
private final FiatRoleConfig fiatRoleConfig;
public BaseServiceAccountResourceProvider(FiatRoleConfig fiatRoleConfig) {
this.fiatRoleConfig = fiatRoleConfig;
}
@Override | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/BaseServiceAccountResourceProvider.java
import com.netflix.spinnaker.fiat.config.FiatRoleConfig;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import lombok.NonNull;
package com.netflix.spinnaker.fiat.providers;
public abstract class BaseServiceAccountResourceProvider
extends BaseResourceProvider<ServiceAccount> {
private final FiatRoleConfig fiatRoleConfig;
public BaseServiceAccountResourceProvider(FiatRoleConfig fiatRoleConfig) {
this.fiatRoleConfig = fiatRoleConfig;
}
@Override | public Set<ServiceAccount> getAllRestricted(@NonNull Set<Role> roles, boolean isAdmin) |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/config/ResourceProvidersHealthIndicator.java | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/HealthTrackable.java
// public interface HealthTrackable {
//
// ProviderHealthTracker getHealthTracker();
// }
| import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spinnaker.fiat.providers.HealthTrackable;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.config;
@Slf4j
@Component
@ConditionalOnExpression("${fiat.write-mode.enabled:true}")
public class ResourceProvidersHealthIndicator extends AbstractHealthIndicator {
| // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/HealthTrackable.java
// public interface HealthTrackable {
//
// ProviderHealthTracker getHealthTracker();
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/config/ResourceProvidersHealthIndicator.java
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spinnaker.fiat.providers.HealthTrackable;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.config;
@Slf4j
@Component
@ConditionalOnExpression("${fiat.write-mode.enabled:true}")
public class ResourceProvidersHealthIndicator extends AbstractHealthIndicator {
| @Autowired @Setter List<HealthTrackable> providers; |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultServiceAccountResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java
// public class Front50Service {
//
// private final Front50ApplicationLoader front50ApplicationLoader;
// private final Front50ServiceAccountLoader front50ServiceAccountLoader;
//
// public Front50Service(
// Front50ApplicationLoader front50ApplicationLoader,
// Front50ServiceAccountLoader front50ServiceAccountLoader) {
// this.front50ApplicationLoader = front50ApplicationLoader;
// this.front50ServiceAccountLoader = front50ServiceAccountLoader;
// }
//
// /** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
// @Deprecated
// public List<Application> getAllApplications(boolean restricted) {
// return getAllApplications();
// }
//
// public List<Application> getAllApplications() {
// return front50ApplicationLoader.getData();
// }
//
// public List<ServiceAccount> getAllServiceAccounts() {
// return front50ServiceAccountLoader.getData();
// }
// }
| import com.netflix.spinnaker.fiat.config.FiatRoleConfig;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import com.netflix.spinnaker.fiat.providers.internal.Front50Service;
import java.util.HashSet;
import java.util.Set;
import lombok.extern.slf4j.Slf4j; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
@Slf4j
public class DefaultServiceAccountResourceProvider extends BaseServiceAccountResourceProvider {
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java
// public class Front50Service {
//
// private final Front50ApplicationLoader front50ApplicationLoader;
// private final Front50ServiceAccountLoader front50ServiceAccountLoader;
//
// public Front50Service(
// Front50ApplicationLoader front50ApplicationLoader,
// Front50ServiceAccountLoader front50ServiceAccountLoader) {
// this.front50ApplicationLoader = front50ApplicationLoader;
// this.front50ServiceAccountLoader = front50ServiceAccountLoader;
// }
//
// /** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
// @Deprecated
// public List<Application> getAllApplications(boolean restricted) {
// return getAllApplications();
// }
//
// public List<Application> getAllApplications() {
// return front50ApplicationLoader.getData();
// }
//
// public List<ServiceAccount> getAllServiceAccounts() {
// return front50ServiceAccountLoader.getData();
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultServiceAccountResourceProvider.java
import com.netflix.spinnaker.fiat.config.FiatRoleConfig;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import com.netflix.spinnaker.fiat.providers.internal.Front50Service;
import java.util.HashSet;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
@Slf4j
public class DefaultServiceAccountResourceProvider extends BaseServiceAccountResourceProvider {
| private final Front50Service front50Service; |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultServiceAccountResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java
// public class Front50Service {
//
// private final Front50ApplicationLoader front50ApplicationLoader;
// private final Front50ServiceAccountLoader front50ServiceAccountLoader;
//
// public Front50Service(
// Front50ApplicationLoader front50ApplicationLoader,
// Front50ServiceAccountLoader front50ServiceAccountLoader) {
// this.front50ApplicationLoader = front50ApplicationLoader;
// this.front50ServiceAccountLoader = front50ServiceAccountLoader;
// }
//
// /** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
// @Deprecated
// public List<Application> getAllApplications(boolean restricted) {
// return getAllApplications();
// }
//
// public List<Application> getAllApplications() {
// return front50ApplicationLoader.getData();
// }
//
// public List<ServiceAccount> getAllServiceAccounts() {
// return front50ServiceAccountLoader.getData();
// }
// }
| import com.netflix.spinnaker.fiat.config.FiatRoleConfig;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import com.netflix.spinnaker.fiat.providers.internal.Front50Service;
import java.util.HashSet;
import java.util.Set;
import lombok.extern.slf4j.Slf4j; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
@Slf4j
public class DefaultServiceAccountResourceProvider extends BaseServiceAccountResourceProvider {
private final Front50Service front50Service;
public DefaultServiceAccountResourceProvider(
Front50Service front50Service, FiatRoleConfig fiatRoleConfig) {
super(fiatRoleConfig);
this.front50Service = front50Service;
}
@Override | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java
// public class Front50Service {
//
// private final Front50ApplicationLoader front50ApplicationLoader;
// private final Front50ServiceAccountLoader front50ServiceAccountLoader;
//
// public Front50Service(
// Front50ApplicationLoader front50ApplicationLoader,
// Front50ServiceAccountLoader front50ServiceAccountLoader) {
// this.front50ApplicationLoader = front50ApplicationLoader;
// this.front50ServiceAccountLoader = front50ServiceAccountLoader;
// }
//
// /** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
// @Deprecated
// public List<Application> getAllApplications(boolean restricted) {
// return getAllApplications();
// }
//
// public List<Application> getAllApplications() {
// return front50ApplicationLoader.getData();
// }
//
// public List<ServiceAccount> getAllServiceAccounts() {
// return front50ServiceAccountLoader.getData();
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultServiceAccountResourceProvider.java
import com.netflix.spinnaker.fiat.config.FiatRoleConfig;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import com.netflix.spinnaker.fiat.providers.internal.Front50Service;
import java.util.HashSet;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
@Slf4j
public class DefaultServiceAccountResourceProvider extends BaseServiceAccountResourceProvider {
private final Front50Service front50Service;
public DefaultServiceAccountResourceProvider(
Front50Service front50Service, FiatRoleConfig fiatRoleConfig) {
super(fiatRoleConfig);
this.front50Service = front50Service;
}
@Override | protected Set<ServiceAccount> loadAll() throws ProviderException { |
spinnaker/fiat | fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.model.resources;
@Component
@Data
@EqualsAndHashCode(callSuper = false)
public class Account extends BaseAccessControlled<Account> implements Viewable {
final ResourceType resourceType = ResourceType.ACCOUNT;
private String name;
private String cloudProvider;
private Permissions permissions = Permissions.EMPTY;
@JsonIgnore
@Override
public View getView(Set<Role> userRoles, boolean isAdmin) {
return new View(this, userRoles, isAdmin);
}
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public static class View extends BaseView implements Authorizable {
String name; | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.model.resources;
@Component
@Data
@EqualsAndHashCode(callSuper = false)
public class Account extends BaseAccessControlled<Account> implements Viewable {
final ResourceType resourceType = ResourceType.ACCOUNT;
private String name;
private String cloudProvider;
private Permissions permissions = Permissions.EMPTY;
@JsonIgnore
@Override
public View getView(Set<Role> userRoles, boolean isAdmin) {
return new View(this, userRoles, isAdmin);
}
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public static class View extends BaseView implements Authorizable {
String name; | Set<Authorization> authorizations; |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverService.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverService {
private final ClouddriverApplicationLoader clouddriverApplicationLoader;
private final ClouddriverAccountLoader clouddriverAccountLoader;
public ClouddriverService(
ClouddriverApplicationLoader clouddriverApplicationLoader,
ClouddriverAccountLoader clouddriverAccountLoader) {
this.clouddriverApplicationLoader = clouddriverApplicationLoader;
this.clouddriverAccountLoader = clouddriverAccountLoader;
}
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverService.java
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverService {
private final ClouddriverApplicationLoader clouddriverApplicationLoader;
private final ClouddriverAccountLoader clouddriverAccountLoader;
public ClouddriverService(
ClouddriverApplicationLoader clouddriverApplicationLoader,
ClouddriverAccountLoader clouddriverAccountLoader) {
this.clouddriverApplicationLoader = clouddriverApplicationLoader;
this.clouddriverAccountLoader = clouddriverAccountLoader;
}
| public List<Account> getAccounts() { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverService.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverService {
private final ClouddriverApplicationLoader clouddriverApplicationLoader;
private final ClouddriverAccountLoader clouddriverAccountLoader;
public ClouddriverService(
ClouddriverApplicationLoader clouddriverApplicationLoader,
ClouddriverAccountLoader clouddriverAccountLoader) {
this.clouddriverApplicationLoader = clouddriverApplicationLoader;
this.clouddriverAccountLoader = clouddriverAccountLoader;
}
public List<Account> getAccounts() {
return clouddriverAccountLoader.getData();
}
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverService.java
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverService {
private final ClouddriverApplicationLoader clouddriverApplicationLoader;
private final ClouddriverAccountLoader clouddriverAccountLoader;
public ClouddriverService(
ClouddriverApplicationLoader clouddriverApplicationLoader,
ClouddriverAccountLoader clouddriverAccountLoader) {
this.clouddriverApplicationLoader = clouddriverApplicationLoader;
this.clouddriverAccountLoader = clouddriverAccountLoader;
}
public List<Account> getAccounts() {
return clouddriverAccountLoader.getData();
}
| public List<Application> getApplications() { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/DefaultFallbackPermissionsResolver.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
// @ToString
// @EqualsAndHashCode
// public class Permissions {
//
// public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
//
// private final Map<Authorization, List<String>> permissions;
//
// private Permissions(Map<Authorization, List<String>> p) {
// this.permissions = Collections.unmodifiableMap(p);
// }
//
// /**
// * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
// * to sanitize the input data (just in case).
// */
// @JsonCreator
// public static Permissions factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data).build();
// }
//
// /** Here specifically for Jackson serialization. */
// @JsonValue
// private Map<Authorization, List<String>> getPermissions() {
// return permissions;
// }
//
// public Set<String> allGroups() {
// return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
// }
//
// /**
// * Determines whether this Permissions has any Authorizations with associated roles.
// *
// * @return whether this Permissions has any Authorizations with associated roles
// * @deprecated check {@code !isRestricted()} instead
// */
// @Deprecated
// public boolean isEmpty() {
// return !isRestricted();
// }
//
// public boolean isRestricted() {
// return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty());
// }
//
// public boolean isAuthorized(Set<Role> userRoles) {
// return !getAuthorizations(userRoles).isEmpty();
// }
//
// public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
// val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
// return getAuthorizations(r);
// }
//
// public Set<Authorization> getAuthorizations(List<String> userRoles) {
// if (!isRestricted()) {
// return Authorization.ALL;
// }
//
// return this.permissions.entrySet().stream()
// .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
// }
//
// public List<String> get(Authorization a) {
// return permissions.getOrDefault(a, new ArrayList<>());
// }
//
// public Map<Authorization, List<String>> unpack() {
// return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
// }
//
// /**
// * This is a helper class for setting up an immutable Permissions object. It also acts as the
// * target Java Object for Spring's ConfigurationProperties deserialization.
// *
// * <p>Objects should be defined on the account config like:
// *
// * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1
// *
// * <p>Group/Role names are trimmed of whitespace and lowercased.
// */
// public static class Builder extends LinkedHashMap<Authorization, List<String>> {
//
// private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
// final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
// for (Authorization auth : Authorization.values()) {
// Optional.ofNullable(authConfig.get(auth))
// .map(
// groups ->
// groups.stream()
// .map(String::trim)
// .filter(s -> !s.isEmpty())
// .map(String::toLowerCase)
// .collect(Collectors.toList()))
// .filter(g -> !g.isEmpty())
// .map(Collections::unmodifiableList)
// .ifPresent(roles -> perms.put(auth, roles));
// }
// return new Permissions(perms);
// }
//
// @JsonCreator
// public static Builder factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data);
// }
//
// public Builder set(Map<Authorization, List<String>> p) {
// this.clear();
// this.putAll(p);
// return this;
// }
//
// public Builder add(Authorization a, String group) {
// this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
// return this;
// }
//
// public Builder add(Authorization a, List<String> groups) {
// groups.forEach(group -> add(a, group));
// return this;
// }
//
// public Permissions build() {
// final Permissions result = fromMap(this);
// if (!result.isRestricted()) {
// return Permissions.EMPTY;
// }
// return result;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.Authorization;
import com.netflix.spinnaker.fiat.model.resources.Permissions;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull; | package com.netflix.spinnaker.fiat.permissions;
public class DefaultFallbackPermissionsResolver implements FallbackPermissionsResolver {
private final Authorization fallbackFrom;
private final Authorization fallbackTo;
public DefaultFallbackPermissionsResolver(Authorization fallbackFrom, Authorization fallbackTo) {
this.fallbackFrom = fallbackFrom;
this.fallbackTo = fallbackTo;
}
@Override | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
// @ToString
// @EqualsAndHashCode
// public class Permissions {
//
// public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
//
// private final Map<Authorization, List<String>> permissions;
//
// private Permissions(Map<Authorization, List<String>> p) {
// this.permissions = Collections.unmodifiableMap(p);
// }
//
// /**
// * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
// * to sanitize the input data (just in case).
// */
// @JsonCreator
// public static Permissions factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data).build();
// }
//
// /** Here specifically for Jackson serialization. */
// @JsonValue
// private Map<Authorization, List<String>> getPermissions() {
// return permissions;
// }
//
// public Set<String> allGroups() {
// return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
// }
//
// /**
// * Determines whether this Permissions has any Authorizations with associated roles.
// *
// * @return whether this Permissions has any Authorizations with associated roles
// * @deprecated check {@code !isRestricted()} instead
// */
// @Deprecated
// public boolean isEmpty() {
// return !isRestricted();
// }
//
// public boolean isRestricted() {
// return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty());
// }
//
// public boolean isAuthorized(Set<Role> userRoles) {
// return !getAuthorizations(userRoles).isEmpty();
// }
//
// public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
// val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
// return getAuthorizations(r);
// }
//
// public Set<Authorization> getAuthorizations(List<String> userRoles) {
// if (!isRestricted()) {
// return Authorization.ALL;
// }
//
// return this.permissions.entrySet().stream()
// .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
// }
//
// public List<String> get(Authorization a) {
// return permissions.getOrDefault(a, new ArrayList<>());
// }
//
// public Map<Authorization, List<String>> unpack() {
// return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
// }
//
// /**
// * This is a helper class for setting up an immutable Permissions object. It also acts as the
// * target Java Object for Spring's ConfigurationProperties deserialization.
// *
// * <p>Objects should be defined on the account config like:
// *
// * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1
// *
// * <p>Group/Role names are trimmed of whitespace and lowercased.
// */
// public static class Builder extends LinkedHashMap<Authorization, List<String>> {
//
// private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
// final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
// for (Authorization auth : Authorization.values()) {
// Optional.ofNullable(authConfig.get(auth))
// .map(
// groups ->
// groups.stream()
// .map(String::trim)
// .filter(s -> !s.isEmpty())
// .map(String::toLowerCase)
// .collect(Collectors.toList()))
// .filter(g -> !g.isEmpty())
// .map(Collections::unmodifiableList)
// .ifPresent(roles -> perms.put(auth, roles));
// }
// return new Permissions(perms);
// }
//
// @JsonCreator
// public static Builder factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data);
// }
//
// public Builder set(Map<Authorization, List<String>> p) {
// this.clear();
// this.putAll(p);
// return this;
// }
//
// public Builder add(Authorization a, String group) {
// this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
// return this;
// }
//
// public Builder add(Authorization a, List<String> groups) {
// groups.forEach(group -> add(a, group));
// return this;
// }
//
// public Permissions build() {
// final Permissions result = fromMap(this);
// if (!result.isRestricted()) {
// return Permissions.EMPTY;
// }
// return result;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/DefaultFallbackPermissionsResolver.java
import com.netflix.spinnaker.fiat.model.Authorization;
import com.netflix.spinnaker.fiat.model.resources.Permissions;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
package com.netflix.spinnaker.fiat.permissions;
public class DefaultFallbackPermissionsResolver implements FallbackPermissionsResolver {
private final Authorization fallbackFrom;
private final Authorization fallbackTo;
public DefaultFallbackPermissionsResolver(Authorization fallbackFrom, Authorization fallbackTo) {
this.fallbackFrom = fallbackFrom;
this.fallbackTo = fallbackTo;
}
@Override | public boolean shouldResolve(@Nonnull Permissions permissions) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultBuildServiceResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorService.java
// public class IgorService {
//
// private final IgorBuildServiceLoader igorBuildServiceLoader;
//
// public IgorService(IgorBuildServiceLoader igorBuildServiceLoader) {
// this.igorBuildServiceLoader = igorBuildServiceLoader;
// }
//
// public List<BuildService> getAllBuildServices() {
// return igorBuildServiceLoader.getData();
// }
// }
| import com.google.common.collect.ImmutableSet;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.internal.IgorService;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component; | /*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
@Component
@ConditionalOnProperty("services.igor.enabled") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorService.java
// public class IgorService {
//
// private final IgorBuildServiceLoader igorBuildServiceLoader;
//
// public IgorService(IgorBuildServiceLoader igorBuildServiceLoader) {
// this.igorBuildServiceLoader = igorBuildServiceLoader;
// }
//
// public List<BuildService> getAllBuildServices() {
// return igorBuildServiceLoader.getData();
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultBuildServiceResourceProvider.java
import com.google.common.collect.ImmutableSet;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.internal.IgorService;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
/*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
@Component
@ConditionalOnProperty("services.igor.enabled") | public class DefaultBuildServiceResourceProvider extends BaseResourceProvider<BuildService> |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultBuildServiceResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorService.java
// public class IgorService {
//
// private final IgorBuildServiceLoader igorBuildServiceLoader;
//
// public IgorService(IgorBuildServiceLoader igorBuildServiceLoader) {
// this.igorBuildServiceLoader = igorBuildServiceLoader;
// }
//
// public List<BuildService> getAllBuildServices() {
// return igorBuildServiceLoader.getData();
// }
// }
| import com.google.common.collect.ImmutableSet;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.internal.IgorService;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component; | /*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
@Component
@ConditionalOnProperty("services.igor.enabled")
public class DefaultBuildServiceResourceProvider extends BaseResourceProvider<BuildService>
implements ResourceProvider<BuildService> {
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorService.java
// public class IgorService {
//
// private final IgorBuildServiceLoader igorBuildServiceLoader;
//
// public IgorService(IgorBuildServiceLoader igorBuildServiceLoader) {
// this.igorBuildServiceLoader = igorBuildServiceLoader;
// }
//
// public List<BuildService> getAllBuildServices() {
// return igorBuildServiceLoader.getData();
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultBuildServiceResourceProvider.java
import com.google.common.collect.ImmutableSet;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.internal.IgorService;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
/*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
@Component
@ConditionalOnProperty("services.igor.enabled")
public class DefaultBuildServiceResourceProvider extends BaseResourceProvider<BuildService>
implements ResourceProvider<BuildService> {
| private final IgorService igorService; |
spinnaker/fiat | fiat-google-groups/src/main/java/com/netflix/spinnaker/fiat/roles/google/GoogleDirectoryUserRolesProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
| import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.Group;
import com.google.api.services.admin.directory.model.Groups;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.PropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.roles.google;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "google") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
// Path: fiat-google-groups/src/main/java/com/netflix/spinnaker/fiat/roles/google/GoogleDirectoryUserRolesProvider.java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.Group;
import com.google.api.services.admin.directory.model.Groups;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.PropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.roles.google;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "google") | public class GoogleDirectoryUserRolesProvider implements UserRolesProvider, InitializingBean { |
spinnaker/fiat | fiat-google-groups/src/main/java/com/netflix/spinnaker/fiat/roles/google/GoogleDirectoryUserRolesProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
| import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.Group;
import com.google.api.services.admin.directory.model.Groups;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.PropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert; | Assert.state(config.getAdminUsername() != null, "Supply an admin username");
}
@Data
@EqualsAndHashCode(callSuper = true)
private class GroupBatchCallback extends JsonBatchCallback<Groups> {
Map<String, Collection<Role>> emailGroupsMap;
String email;
@Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
log.warn("Failed to fetch groups for user " + email + ": " + e.getMessage());
}
@Override
public void onSuccess(Groups groups, HttpHeaders responseHeaders) throws IOException {
if (groups == null || groups.getGroups() == null || groups.getGroups().isEmpty()) {
log.debug("No groups found for user " + email);
return;
}
Set<Role> groupSet =
groups.getGroups().stream().flatMap(toRoleFn()).collect(Collectors.toSet());
emailGroupsMap.put(email, groupSet);
}
}
@Override | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
// Path: fiat-google-groups/src/main/java/com/netflix/spinnaker/fiat/roles/google/GoogleDirectoryUserRolesProvider.java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.Group;
import com.google.api.services.admin.directory.model.Groups;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.PropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
Assert.state(config.getAdminUsername() != null, "Supply an admin username");
}
@Data
@EqualsAndHashCode(callSuper = true)
private class GroupBatchCallback extends JsonBatchCallback<Groups> {
Map<String, Collection<Role>> emailGroupsMap;
String email;
@Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
log.warn("Failed to fetch groups for user " + email + ": " + e.getMessage());
}
@Override
public void onSuccess(Groups groups, HttpHeaders responseHeaders) throws IOException {
if (groups == null || groups.getGroups() == null || groups.getGroups().isEmpty()) {
log.debug("No groups found for user " + email);
return;
}
Set<Role> groupSet =
groups.getGroups().stream().flatMap(toRoleFn()).collect(Collectors.toSet());
emailGroupsMap.put(email, groupSet);
}
}
@Override | public Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
| import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.roles;
public interface UserRolesProvider {
default List<Role> loadUnrestrictedRoles() {
return new ArrayList<>();
}
/**
* Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
* user}.
*
* @param user to load roles for
* @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
* with the given id.
*/ | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.roles;
public interface UserRolesProvider {
default List<Role> loadUnrestrictedRoles() {
return new ArrayList<>();
}
/**
* Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
* user}.
*
* @param user to load roles for
* @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
* with the given id.
*/ | List<Role> loadRoles(ExternalUser user); |
spinnaker/fiat | fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/UserPermission.java
// @Data
// public class UserPermission {
// private String id;
//
// private Set<Account> accounts = new LinkedHashSet<>();
// private Set<Application> applications = new LinkedHashSet<>();
// private Set<ServiceAccount> serviceAccounts = new LinkedHashSet<>();
// private Set<Role> roles = new LinkedHashSet<>();
// private Set<BuildService> buildServices = new LinkedHashSet<>();
// private Set<Resource> extensionResources = new LinkedHashSet<>();
// private boolean admin = false;
//
// /**
// * Custom setter to normalize the input. lombok.accessors.chain is enabled, so setters must return
// * {@code this}.
// */
// public UserPermission setId(String id) {
// this.id = id.toLowerCase();
// return this;
// }
//
// /** Custom getter to normalize the output. */
// public String getId() {
// return this.id.toLowerCase();
// }
//
// public void addResource(Resource resource) {
// addResources(Collections.singleton(resource));
// }
//
// public UserPermission addResources(Collection<Resource> resources) {
// if (resources == null) {
// return this;
// }
//
// resources.forEach(
// resource -> {
// if (resource instanceof Account) {
// accounts.add((Account) resource);
// } else if (resource instanceof Application) {
// applications.add((Application) resource);
// } else if (resource instanceof ServiceAccount) {
// serviceAccounts.add((ServiceAccount) resource);
// } else if (resource instanceof Role) {
// roles.add((Role) resource);
// } else if (resource instanceof BuildService) {
// buildServices.add((BuildService) resource);
// } else {
// extensionResources.add(resource);
// }
// });
//
// return this;
// }
//
// @JsonIgnore
// public Set<Resource> getAllResources() {
// Set<Resource> retVal = new HashSet<>();
// retVal.addAll(accounts);
// retVal.addAll(applications);
// retVal.addAll(serviceAccounts);
// retVal.addAll(roles);
// retVal.addAll(buildServices);
// retVal.addAll(extensionResources);
// return retVal;
// }
//
// /**
// * This method adds all of other's resources to this one.
// *
// * @param other
// */
// public UserPermission merge(UserPermission other) {
// this.addResources(other.getAllResources());
// return this;
// }
//
// @JsonIgnore
// public View getView() {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// @SuppressWarnings("unchecked")
// public static class View extends Viewable.BaseView {
// String name;
// Set<Account.View> accounts;
// Set<Application.View> applications;
// Set<ServiceAccount.View> serviceAccounts;
// Set<Role.View> roles;
// Set<BuildService.View> buildServices;
// HashMap<ResourceType, Set<Authorizable>> extensionResources;
// boolean admin;
// boolean legacyFallback = false;
// boolean allowAccessToUnknownApplications = false;
//
// public View(UserPermission permission) {
// this.name = permission.id;
//
// Function<Set<? extends Viewable>, Set<? extends Viewable.BaseView>> toViews =
// sourceSet ->
// sourceSet.stream()
// .map(viewable -> viewable.getView(permission.getRoles(), permission.isAdmin()))
// .collect(Collectors.toSet());
//
// this.accounts = (Set<Account.View>) toViews.apply(permission.getAccounts());
// this.applications = (Set<Application.View>) toViews.apply(permission.getApplications());
// this.serviceAccounts =
// (Set<ServiceAccount.View>) toViews.apply(permission.getServiceAccounts());
// this.roles = (Set<Role.View>) toViews.apply(permission.getRoles());
// this.buildServices = (Set<BuildService.View>) toViews.apply(permission.getBuildServices());
//
// this.extensionResources = new HashMap<>();
// for (val resource : permission.extensionResources) {
// val set =
// this.extensionResources.computeIfAbsent(
// resource.getResourceType(), (ignore) -> new HashSet<>());
// val view = ((Viewable) resource).getView(permission.getRoles(), permission.isAdmin());
// if (view instanceof Authorizable) {
// set.add((Authorizable) view);
// }
// }
//
// this.admin = permission.isAdmin();
// }
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.spinnaker.fiat.model.UserPermission;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.model.resources;
@Component
@Data
@EqualsAndHashCode(callSuper = false)
public class ServiceAccount implements Resource, Viewable {
private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
private String name;
private List<String> memberOf = new ArrayList<>();
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/UserPermission.java
// @Data
// public class UserPermission {
// private String id;
//
// private Set<Account> accounts = new LinkedHashSet<>();
// private Set<Application> applications = new LinkedHashSet<>();
// private Set<ServiceAccount> serviceAccounts = new LinkedHashSet<>();
// private Set<Role> roles = new LinkedHashSet<>();
// private Set<BuildService> buildServices = new LinkedHashSet<>();
// private Set<Resource> extensionResources = new LinkedHashSet<>();
// private boolean admin = false;
//
// /**
// * Custom setter to normalize the input. lombok.accessors.chain is enabled, so setters must return
// * {@code this}.
// */
// public UserPermission setId(String id) {
// this.id = id.toLowerCase();
// return this;
// }
//
// /** Custom getter to normalize the output. */
// public String getId() {
// return this.id.toLowerCase();
// }
//
// public void addResource(Resource resource) {
// addResources(Collections.singleton(resource));
// }
//
// public UserPermission addResources(Collection<Resource> resources) {
// if (resources == null) {
// return this;
// }
//
// resources.forEach(
// resource -> {
// if (resource instanceof Account) {
// accounts.add((Account) resource);
// } else if (resource instanceof Application) {
// applications.add((Application) resource);
// } else if (resource instanceof ServiceAccount) {
// serviceAccounts.add((ServiceAccount) resource);
// } else if (resource instanceof Role) {
// roles.add((Role) resource);
// } else if (resource instanceof BuildService) {
// buildServices.add((BuildService) resource);
// } else {
// extensionResources.add(resource);
// }
// });
//
// return this;
// }
//
// @JsonIgnore
// public Set<Resource> getAllResources() {
// Set<Resource> retVal = new HashSet<>();
// retVal.addAll(accounts);
// retVal.addAll(applications);
// retVal.addAll(serviceAccounts);
// retVal.addAll(roles);
// retVal.addAll(buildServices);
// retVal.addAll(extensionResources);
// return retVal;
// }
//
// /**
// * This method adds all of other's resources to this one.
// *
// * @param other
// */
// public UserPermission merge(UserPermission other) {
// this.addResources(other.getAllResources());
// return this;
// }
//
// @JsonIgnore
// public View getView() {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// @SuppressWarnings("unchecked")
// public static class View extends Viewable.BaseView {
// String name;
// Set<Account.View> accounts;
// Set<Application.View> applications;
// Set<ServiceAccount.View> serviceAccounts;
// Set<Role.View> roles;
// Set<BuildService.View> buildServices;
// HashMap<ResourceType, Set<Authorizable>> extensionResources;
// boolean admin;
// boolean legacyFallback = false;
// boolean allowAccessToUnknownApplications = false;
//
// public View(UserPermission permission) {
// this.name = permission.id;
//
// Function<Set<? extends Viewable>, Set<? extends Viewable.BaseView>> toViews =
// sourceSet ->
// sourceSet.stream()
// .map(viewable -> viewable.getView(permission.getRoles(), permission.isAdmin()))
// .collect(Collectors.toSet());
//
// this.accounts = (Set<Account.View>) toViews.apply(permission.getAccounts());
// this.applications = (Set<Application.View>) toViews.apply(permission.getApplications());
// this.serviceAccounts =
// (Set<ServiceAccount.View>) toViews.apply(permission.getServiceAccounts());
// this.roles = (Set<Role.View>) toViews.apply(permission.getRoles());
// this.buildServices = (Set<BuildService.View>) toViews.apply(permission.getBuildServices());
//
// this.extensionResources = new HashMap<>();
// for (val resource : permission.extensionResources) {
// val set =
// this.extensionResources.computeIfAbsent(
// resource.getResourceType(), (ignore) -> new HashSet<>());
// val view = ((Viewable) resource).getView(permission.getRoles(), permission.isAdmin());
// if (view instanceof Authorizable) {
// set.add((Authorizable) view);
// }
// }
//
// this.admin = permission.isAdmin();
// }
// }
// }
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.spinnaker.fiat.model.UserPermission;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.model.resources;
@Component
@Data
@EqualsAndHashCode(callSuper = false)
public class ServiceAccount implements Resource, Viewable {
private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
private String name;
private List<String> memberOf = new ArrayList<>();
| public UserPermission toUserPermission() { |
spinnaker/fiat | fiat-file/src/main/java/com/netflix/spinnaker/fiat/roles/file/FileBasedUserRolesProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component; | /*
* Copyright 2017 Google, 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 com.netflix.spinnaker.fiat.roles.file;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "file") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
// Path: fiat-file/src/main/java/com/netflix/spinnaker/fiat/roles/file/FileBasedUserRolesProvider.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/*
* Copyright 2017 Google, 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 com.netflix.spinnaker.fiat.roles.file;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "file") | public class FileBasedUserRolesProvider implements UserRolesProvider { |
spinnaker/fiat | fiat-file/src/main/java/com/netflix/spinnaker/fiat/roles/file/FileBasedUserRolesProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component; | /*
* Copyright 2017 Google, 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 com.netflix.spinnaker.fiat.roles.file;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "file")
public class FileBasedUserRolesProvider implements UserRolesProvider {
@Autowired ConfigProps configProps;
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
// Path: fiat-file/src/main/java/com/netflix/spinnaker/fiat/roles/file/FileBasedUserRolesProvider.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/*
* Copyright 2017 Google, 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 com.netflix.spinnaker.fiat.roles.file;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "file")
public class FileBasedUserRolesProvider implements UserRolesProvider {
@Autowired ConfigProps configProps;
| private Map<String, List<Role>> parse() throws IOException { |
spinnaker/fiat | fiat-file/src/main/java/com/netflix/spinnaker/fiat/roles/file/FileBasedUserRolesProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component; | /*
* Copyright 2017 Google, 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 com.netflix.spinnaker.fiat.roles.file;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "file")
public class FileBasedUserRolesProvider implements UserRolesProvider {
@Autowired ConfigProps configProps;
private Map<String, List<Role>> parse() throws IOException {
return parse(new BufferedReader(new FileReader(new File(configProps.getPath()))));
}
private Map<String, List<Role>> parse(Reader source) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(source, UserRolesMapping.class).toMap();
}
@Override | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
// @Data
// public class ExternalUser {
// private String id;
// private List<Role> externalRoles = new ArrayList<>();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/roles/UserRolesProvider.java
// public interface UserRolesProvider {
//
// default List<Role> loadUnrestrictedRoles() {
// return new ArrayList<>();
// }
//
// /**
// * Load the roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user}.
// *
// * @param user to load roles for
// * @return Roles assigned to the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser user}
// * with the given id.
// */
// List<Role> loadRoles(ExternalUser user);
//
// /**
// * Load the roles assigned to each {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id in users.
// *
// * @param users to load roles for
// * @return Map whose keys are the {@link com.netflix.spinnaker.fiat.permissions.ExternalUser
// * user's} id and values are their assigned roles.
// */
// Map<String, Collection<Role>> multiLoadRoles(Collection<ExternalUser> users);
// }
// Path: fiat-file/src/main/java/com/netflix/spinnaker/fiat/roles/file/FileBasedUserRolesProvider.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.roles.UserRolesProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/*
* Copyright 2017 Google, 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 com.netflix.spinnaker.fiat.roles.file;
@Slf4j
@Component
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "file")
public class FileBasedUserRolesProvider implements UserRolesProvider {
@Autowired ConfigProps configProps;
private Map<String, List<Role>> parse() throws IOException {
return parse(new BufferedReader(new FileReader(new File(configProps.getPath()))));
}
private Map<String, List<Role>> parse(Reader source) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(source, UserRolesMapping.class).toMap();
}
@Override | public List<Role> loadRoles(ExternalUser user) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverApi.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List;
import retrofit.http.GET; | /*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface ClouddriverApi {
@GET("/credentials") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverApi.java
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List;
import retrofit.http.GET;
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface ClouddriverApi {
@GET("/credentials") | List<Account> getAccounts(); |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverApi.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List;
import retrofit.http.GET; | /*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface ClouddriverApi {
@GET("/credentials")
List<Account> getAccounts();
@GET("/applications?restricted=false&expand=false") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverApi.java
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import java.util.List;
import retrofit.http.GET;
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface ClouddriverApi {
@GET("/credentials")
List<Account> getAccounts();
@GET("/applications?restricted=false&expand=false") | List<Application> getApplications(); |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/DataLoader.java | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/HealthTrackable.java
// public interface HealthTrackable {
//
// ProviderHealthTracker getHealthTracker();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
| import static com.netflix.spinnaker.security.AuthenticatedRequest.allowAnonymous;
import com.netflix.spinnaker.fiat.providers.HealthTrackable;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent; | /*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public class DataLoader<T> implements HealthTrackable, ApplicationListener<ContextRefreshedEvent> {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Supplier<List<T>> loadingFunction; | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/HealthTrackable.java
// public interface HealthTrackable {
//
// ProviderHealthTracker getHealthTracker();
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/DataLoader.java
import static com.netflix.spinnaker.security.AuthenticatedRequest.allowAnonymous;
import com.netflix.spinnaker.fiat.providers.HealthTrackable;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
/*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public class DataLoader<T> implements HealthTrackable, ApplicationListener<ContextRefreshedEvent> {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Supplier<List<T>> loadingFunction; | private final ProviderHealthTracker healthTracker; |
spinnaker/fiat | fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/ResourcesConfig.java | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.jakewharton.retrofit.Ok3Client;
import com.netflix.spinnaker.config.DefaultServiceEndpoint;
import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
import com.netflix.spinnaker.fiat.providers.internal.*;
import com.netflix.spinnaker.retrofit.Slf4jRetrofitLogger;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import retrofit.Endpoints;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter; | @Autowired @Setter private OkHttpClientProvider clientProvider;
@Value("${services.front50.base-url}")
@Setter
private String front50Endpoint;
@Value("${services.clouddriver.base-url}")
@Setter
private String clouddriverEndpoint;
@Value("${services.igor.base-url}")
@Setter
private String igorEndpoint;
@Bean
Front50Api front50Api() {
return new RestAdapter.Builder()
.setEndpoint(Endpoints.newFixedEndpoint(front50Endpoint))
.setClient(
new Ok3Client(
clientProvider.getClient(new DefaultServiceEndpoint("front50", front50Endpoint))))
.setConverter(new JacksonConverter(objectMapper))
.setLogLevel(retrofitLogLevel)
.setLog(new Slf4jRetrofitLogger(Front50Api.class))
.build()
.create(Front50Api.class);
}
@Bean
Front50ApplicationLoader front50ApplicationLoader( | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
// Path: fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/ResourcesConfig.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jakewharton.retrofit.Ok3Client;
import com.netflix.spinnaker.config.DefaultServiceEndpoint;
import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
import com.netflix.spinnaker.fiat.providers.internal.*;
import com.netflix.spinnaker.retrofit.Slf4jRetrofitLogger;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import retrofit.Endpoints;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter;
@Autowired @Setter private OkHttpClientProvider clientProvider;
@Value("${services.front50.base-url}")
@Setter
private String front50Endpoint;
@Value("${services.clouddriver.base-url}")
@Setter
private String clouddriverEndpoint;
@Value("${services.igor.base-url}")
@Setter
private String igorEndpoint;
@Bean
Front50Api front50Api() {
return new RestAdapter.Builder()
.setEndpoint(Endpoints.newFixedEndpoint(front50Endpoint))
.setClient(
new Ok3Client(
clientProvider.getClient(new DefaultServiceEndpoint("front50", front50Endpoint))))
.setConverter(new JacksonConverter(objectMapper))
.setLogLevel(retrofitLogLevel)
.setLog(new Slf4jRetrofitLogger(Front50Api.class))
.build()
.create(Front50Api.class);
}
@Bean
Front50ApplicationLoader front50ApplicationLoader( | ProviderHealthTracker tracker, Front50Api front50Api) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverAccountLoader.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker; | /*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverAccountLoader extends ClouddriverDataLoader<Account> {
public ClouddriverAccountLoader( | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverAccountLoader.java
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
/*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverAccountLoader extends ClouddriverDataLoader<Account> {
public ClouddriverAccountLoader( | ProviderHealthTracker healthTracker, ClouddriverApi clouddriverApi) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverDataLoader.java | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
| import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.scheduling.annotation.Scheduled; | /*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
/**
* This class makes and caches live calls to Clouddriver. In the event that Clouddriver is
* unavailable, the cached data is returned in stead. Failed calls are logged with the Clouddriver
* health tracker, which will turn unhealthy after X number of failed cache refreshes.
*/
public class ClouddriverDataLoader<T> extends DataLoader<T> {
public ClouddriverDataLoader( | // Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverDataLoader.java
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.scheduling.annotation.Scheduled;
/*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
/**
* This class makes and caches live calls to Clouddriver. In the event that Clouddriver is
* unavailable, the cached data is returned in stead. Failed calls are logged with the Clouddriver
* health tracker, which will turn unhealthy after X number of failed cache refreshes.
*/
public class ClouddriverDataLoader<T> extends DataLoader<T> {
public ClouddriverDataLoader( | ProviderHealthTracker healthTracker, Supplier<List<T>> loadingFunction) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Resource;
import com.netflix.spinnaker.fiat.model.resources.Role;
import java.util.Set; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
public interface ResourceProvider<R extends Resource> {
Set<R> getAll() throws ProviderException;
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ResourceProvider.java
import com.netflix.spinnaker.fiat.model.resources.Resource;
import com.netflix.spinnaker.fiat.model.resources.Role;
import java.util.Set;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
public interface ResourceProvider<R extends Resource> {
Set<R> getAll() throws ProviderException;
| Set<R> getAllRestricted(Set<Role> roles, boolean isAdmin) throws ProviderException; |
spinnaker/fiat | fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/DefaultResourcePermissionConfig.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; | /*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.config;
@Configuration
class DefaultResourcePermissionConfig {
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.account.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100) | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/DefaultResourcePermissionConfig.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.config;
@Configuration
class DefaultResourcePermissionConfig {
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.account.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100) | ResourcePermissionSource<Account> accountResourcePermissionSource() { |
spinnaker/fiat | fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/DefaultResourcePermissionConfig.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; | /*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.config;
@Configuration
class DefaultResourcePermissionConfig {
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.account.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
ResourcePermissionSource<Account> accountResourcePermissionSource() {
return new AccessControlledResourcePermissionSource<>();
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.provider.account",
havingValue = "default",
matchIfMissing = true)
public ResourcePermissionProvider<Account> defaultAccountPermissionProvider(
ResourcePermissionSource<Account> accountResourcePermissionSource) {
return new DefaultResourcePermissionProvider<>(accountResourcePermissionSource);
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.application.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100) | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/DefaultResourcePermissionConfig.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.config;
@Configuration
class DefaultResourcePermissionConfig {
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.account.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
ResourcePermissionSource<Account> accountResourcePermissionSource() {
return new AccessControlledResourcePermissionSource<>();
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.provider.account",
havingValue = "default",
matchIfMissing = true)
public ResourcePermissionProvider<Account> defaultAccountPermissionProvider(
ResourcePermissionSource<Account> accountResourcePermissionSource) {
return new DefaultResourcePermissionProvider<>(accountResourcePermissionSource);
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.application.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100) | ResourcePermissionSource<Application> applicationResourcePermissionSource() { |
spinnaker/fiat | fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/DefaultResourcePermissionConfig.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; | matchIfMissing = true)
public ResourcePermissionProvider<Account> defaultAccountPermissionProvider(
ResourcePermissionSource<Account> accountResourcePermissionSource) {
return new DefaultResourcePermissionProvider<>(accountResourcePermissionSource);
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.application.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
ResourcePermissionSource<Application> applicationResourcePermissionSource() {
return new ApplicationResourcePermissionSource();
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.provider.application",
havingValue = "default",
matchIfMissing = true)
public ResourcePermissionProvider<Application> defaultApplicationPermissionProvider(
ResourcePermissionSource<Application> applicationResourcePermissionSource) {
return new DefaultResourcePermissionProvider<>(applicationResourcePermissionSource);
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.build-service.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100) | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-web/src/main/java/com/netflix/spinnaker/fiat/config/DefaultResourcePermissionConfig.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import com.netflix.spinnaker.fiat.providers.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
matchIfMissing = true)
public ResourcePermissionProvider<Account> defaultAccountPermissionProvider(
ResourcePermissionSource<Account> accountResourcePermissionSource) {
return new DefaultResourcePermissionProvider<>(accountResourcePermissionSource);
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.application.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
ResourcePermissionSource<Application> applicationResourcePermissionSource() {
return new ApplicationResourcePermissionSource();
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.provider.application",
havingValue = "default",
matchIfMissing = true)
public ResourcePermissionProvider<Application> defaultApplicationPermissionProvider(
ResourcePermissionSource<Application> applicationResourcePermissionSource) {
return new DefaultResourcePermissionProvider<>(applicationResourcePermissionSource);
}
@Bean
@ConditionalOnProperty(
value = "auth.permissions.source.build-service.resource.enabled",
matchIfMissing = true)
@Order(Ordered.HIGHEST_PRECEDENCE + 100) | ResourcePermissionSource<BuildService> buildServiceResourcePermissionSource() { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorService.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.BuildService;
import java.util.List; | /*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers.internal;
public class IgorService {
private final IgorBuildServiceLoader igorBuildServiceLoader;
public IgorService(IgorBuildServiceLoader igorBuildServiceLoader) {
this.igorBuildServiceLoader = igorBuildServiceLoader;
}
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BuildService.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class BuildService implements Resource.AccessControlled, Viewable {
//
// private final ResourceType resourceType = ResourceType.BUILD_SERVICE;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// @Override
// public BaseView getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends Viewable.BaseView implements Authorizable {
//
// private String name;
// Set<Authorization> authorizations;
//
// public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
// this.name = buildService.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = buildService.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/IgorService.java
import com.netflix.spinnaker.fiat.model.resources.BuildService;
import java.util.List;
/*
* Copyright 2019 Schibsted ASA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers.internal;
public class IgorService {
private final IgorBuildServiceLoader igorBuildServiceLoader;
public IgorService(IgorBuildServiceLoader igorBuildServiceLoader) {
this.igorBuildServiceLoader = igorBuildServiceLoader;
}
| public List<BuildService> getAllBuildServices() { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ResourcePermissionProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
// @ToString
// @EqualsAndHashCode
// public class Permissions {
//
// public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
//
// private final Map<Authorization, List<String>> permissions;
//
// private Permissions(Map<Authorization, List<String>> p) {
// this.permissions = Collections.unmodifiableMap(p);
// }
//
// /**
// * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
// * to sanitize the input data (just in case).
// */
// @JsonCreator
// public static Permissions factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data).build();
// }
//
// /** Here specifically for Jackson serialization. */
// @JsonValue
// private Map<Authorization, List<String>> getPermissions() {
// return permissions;
// }
//
// public Set<String> allGroups() {
// return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
// }
//
// /**
// * Determines whether this Permissions has any Authorizations with associated roles.
// *
// * @return whether this Permissions has any Authorizations with associated roles
// * @deprecated check {@code !isRestricted()} instead
// */
// @Deprecated
// public boolean isEmpty() {
// return !isRestricted();
// }
//
// public boolean isRestricted() {
// return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty());
// }
//
// public boolean isAuthorized(Set<Role> userRoles) {
// return !getAuthorizations(userRoles).isEmpty();
// }
//
// public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
// val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
// return getAuthorizations(r);
// }
//
// public Set<Authorization> getAuthorizations(List<String> userRoles) {
// if (!isRestricted()) {
// return Authorization.ALL;
// }
//
// return this.permissions.entrySet().stream()
// .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
// }
//
// public List<String> get(Authorization a) {
// return permissions.getOrDefault(a, new ArrayList<>());
// }
//
// public Map<Authorization, List<String>> unpack() {
// return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
// }
//
// /**
// * This is a helper class for setting up an immutable Permissions object. It also acts as the
// * target Java Object for Spring's ConfigurationProperties deserialization.
// *
// * <p>Objects should be defined on the account config like:
// *
// * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1
// *
// * <p>Group/Role names are trimmed of whitespace and lowercased.
// */
// public static class Builder extends LinkedHashMap<Authorization, List<String>> {
//
// private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
// final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
// for (Authorization auth : Authorization.values()) {
// Optional.ofNullable(authConfig.get(auth))
// .map(
// groups ->
// groups.stream()
// .map(String::trim)
// .filter(s -> !s.isEmpty())
// .map(String::toLowerCase)
// .collect(Collectors.toList()))
// .filter(g -> !g.isEmpty())
// .map(Collections::unmodifiableList)
// .ifPresent(roles -> perms.put(auth, roles));
// }
// return new Permissions(perms);
// }
//
// @JsonCreator
// public static Builder factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data);
// }
//
// public Builder set(Map<Authorization, List<String>> p) {
// this.clear();
// this.putAll(p);
// return this;
// }
//
// public Builder add(Authorization a, String group) {
// this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
// return this;
// }
//
// public Builder add(Authorization a, List<String> groups) {
// groups.forEach(group -> add(a, group));
// return this;
// }
//
// public Permissions build() {
// final Permissions result = fromMap(this);
// if (!result.isRestricted()) {
// return Permissions.EMPTY;
// }
// return result;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Permissions;
import com.netflix.spinnaker.fiat.model.resources.Resource;
import javax.annotation.Nonnull; | /*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
/**
* A ResourcePermissionProvider is responsible for supplying the full set of Permissions for a
* specific Resource.
*
* <p>Note that while the API signature matches ResourcePermissionSource the intent of
* ResourcePermissionProvider is the interface for consumers interested in the actual Permissions of
* a resource, while ResourcePermissionSource models a single source of Permissions (for example
* CloudDriver as a source of Account permissions).
*
* @param <T> the type of Resource for which this ResourcePermissionProvider supplies Permissions.
*/
public interface ResourcePermissionProvider<T extends Resource> {
/**
* Retrieves Permissions for the supplied resource.
*
* @param resource the resource for which to get permissions (never null)
* @return the Permissions for the resource (never null - use Permissions.EMPTY or apply some
* restriction)
*/
@Nonnull | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
// @ToString
// @EqualsAndHashCode
// public class Permissions {
//
// public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
//
// private final Map<Authorization, List<String>> permissions;
//
// private Permissions(Map<Authorization, List<String>> p) {
// this.permissions = Collections.unmodifiableMap(p);
// }
//
// /**
// * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
// * to sanitize the input data (just in case).
// */
// @JsonCreator
// public static Permissions factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data).build();
// }
//
// /** Here specifically for Jackson serialization. */
// @JsonValue
// private Map<Authorization, List<String>> getPermissions() {
// return permissions;
// }
//
// public Set<String> allGroups() {
// return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
// }
//
// /**
// * Determines whether this Permissions has any Authorizations with associated roles.
// *
// * @return whether this Permissions has any Authorizations with associated roles
// * @deprecated check {@code !isRestricted()} instead
// */
// @Deprecated
// public boolean isEmpty() {
// return !isRestricted();
// }
//
// public boolean isRestricted() {
// return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty());
// }
//
// public boolean isAuthorized(Set<Role> userRoles) {
// return !getAuthorizations(userRoles).isEmpty();
// }
//
// public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
// val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
// return getAuthorizations(r);
// }
//
// public Set<Authorization> getAuthorizations(List<String> userRoles) {
// if (!isRestricted()) {
// return Authorization.ALL;
// }
//
// return this.permissions.entrySet().stream()
// .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
// }
//
// public List<String> get(Authorization a) {
// return permissions.getOrDefault(a, new ArrayList<>());
// }
//
// public Map<Authorization, List<String>> unpack() {
// return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
// }
//
// /**
// * This is a helper class for setting up an immutable Permissions object. It also acts as the
// * target Java Object for Spring's ConfigurationProperties deserialization.
// *
// * <p>Objects should be defined on the account config like:
// *
// * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1
// *
// * <p>Group/Role names are trimmed of whitespace and lowercased.
// */
// public static class Builder extends LinkedHashMap<Authorization, List<String>> {
//
// private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
// final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
// for (Authorization auth : Authorization.values()) {
// Optional.ofNullable(authConfig.get(auth))
// .map(
// groups ->
// groups.stream()
// .map(String::trim)
// .filter(s -> !s.isEmpty())
// .map(String::toLowerCase)
// .collect(Collectors.toList()))
// .filter(g -> !g.isEmpty())
// .map(Collections::unmodifiableList)
// .ifPresent(roles -> perms.put(auth, roles));
// }
// return new Permissions(perms);
// }
//
// @JsonCreator
// public static Builder factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data);
// }
//
// public Builder set(Map<Authorization, List<String>> p) {
// this.clear();
// this.putAll(p);
// return this;
// }
//
// public Builder add(Authorization a, String group) {
// this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
// return this;
// }
//
// public Builder add(Authorization a, List<String> groups) {
// groups.forEach(group -> add(a, group));
// return this;
// }
//
// public Permissions build() {
// final Permissions result = fromMap(this);
// if (!result.isRestricted()) {
// return Permissions.EMPTY;
// }
// return result;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ResourcePermissionProvider.java
import com.netflix.spinnaker.fiat.model.resources.Permissions;
import com.netflix.spinnaker.fiat.model.resources.Resource;
import javax.annotation.Nonnull;
/*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
/**
* A ResourcePermissionProvider is responsible for supplying the full set of Permissions for a
* specific Resource.
*
* <p>Note that while the API signature matches ResourcePermissionSource the intent of
* ResourcePermissionProvider is the interface for consumers interested in the actual Permissions of
* a resource, while ResourcePermissionSource models a single source of Permissions (for example
* CloudDriver as a source of Account permissions).
*
* @param <T> the type of Resource for which this ResourcePermissionProvider supplies Permissions.
*/
public interface ResourcePermissionProvider<T extends Resource> {
/**
* Retrieves Permissions for the supplied resource.
*
* @param resource the resource for which to get permissions (never null)
* @return the Permissions for the resource (never null - use Permissions.EMPTY or apply some
* restriction)
*/
@Nonnull | Permissions getPermissions(@Nonnull T resource); |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultAccountResourceProvider.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverService.java
// public class ClouddriverService {
// private final ClouddriverApplicationLoader clouddriverApplicationLoader;
// private final ClouddriverAccountLoader clouddriverAccountLoader;
//
// public ClouddriverService(
// ClouddriverApplicationLoader clouddriverApplicationLoader,
// ClouddriverAccountLoader clouddriverAccountLoader) {
// this.clouddriverApplicationLoader = clouddriverApplicationLoader;
// this.clouddriverAccountLoader = clouddriverAccountLoader;
// }
//
// public List<Account> getAccounts() {
// return clouddriverAccountLoader.getData();
// }
//
// public List<Application> getApplications() {
// return clouddriverApplicationLoader.getData();
// }
// }
| import com.google.common.collect.ImmutableSet;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.providers.internal.ClouddriverService;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
@Component
public class DefaultAccountResourceProvider extends BaseResourceProvider<Account>
implements ResourceProvider<Account> {
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Account.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends BaseAccessControlled<Account> implements Viewable {
// final ResourceType resourceType = ResourceType.ACCOUNT;
//
// private String name;
// private String cloudProvider;
// private Permissions permissions = Permissions.EMPTY;
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Account account, Set<Role> userRoles, boolean isAdmin) {
// this.name = account.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = account.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverService.java
// public class ClouddriverService {
// private final ClouddriverApplicationLoader clouddriverApplicationLoader;
// private final ClouddriverAccountLoader clouddriverAccountLoader;
//
// public ClouddriverService(
// ClouddriverApplicationLoader clouddriverApplicationLoader,
// ClouddriverAccountLoader clouddriverAccountLoader) {
// this.clouddriverApplicationLoader = clouddriverApplicationLoader;
// this.clouddriverAccountLoader = clouddriverAccountLoader;
// }
//
// public List<Account> getAccounts() {
// return clouddriverAccountLoader.getData();
// }
//
// public List<Application> getApplications() {
// return clouddriverApplicationLoader.getData();
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/DefaultAccountResourceProvider.java
import com.google.common.collect.ImmutableSet;
import com.netflix.spinnaker.fiat.model.resources.Account;
import com.netflix.spinnaker.fiat.providers.internal.ClouddriverService;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers;
@Component
public class DefaultAccountResourceProvider extends BaseResourceProvider<Account>
implements ResourceProvider<Account> {
| private final ClouddriverService clouddriverService; |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverApplicationLoader.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker; | /*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverApplicationLoader extends ClouddriverDataLoader<Application> {
public ClouddriverApplicationLoader( | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/ProviderHealthTracker.java
// public class ProviderHealthTracker {
//
// /** Maximum age of stale data before this instance goes unhealthy. */
// private final long maximumStalenessTimeMs;
//
// private AtomicLong lastSuccessfulUpdateTimeMs = new AtomicLong(-1);
//
// public ProviderHealthTracker(long maximumStalenessTimeMs) {
// this.maximumStalenessTimeMs = maximumStalenessTimeMs;
// }
//
// public void success() {
// lastSuccessfulUpdateTimeMs.set(System.currentTimeMillis());
// }
//
// public boolean isProviderHealthy() {
// return lastSuccessfulUpdateTimeMs.get() != -1 && getStaleness() < maximumStalenessTimeMs;
// }
//
// private long getStaleness() {
// if (lastSuccessfulUpdateTimeMs.get() == -1) {
// return -1;
// }
// return System.currentTimeMillis() - lastSuccessfulUpdateTimeMs.get();
// }
//
// public HealthView getHealthView() {
// return new HealthView();
// }
//
// @Data
// public class HealthView {
// boolean providerHealthy = ProviderHealthTracker.this.isProviderHealthy();
// long msSinceLastSuccess = ProviderHealthTracker.this.getStaleness();
// long lastSuccessfulUpdateTime = ProviderHealthTracker.this.lastSuccessfulUpdateTimeMs.get();
// long maximumStalenessTimeMs = ProviderHealthTracker.this.maximumStalenessTimeMs;
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/ClouddriverApplicationLoader.java
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.providers.ProviderHealthTracker;
/*
* Copyright 2020 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public class ClouddriverApplicationLoader extends ClouddriverDataLoader<Application> {
public ClouddriverApplicationLoader( | ProviderHealthTracker healthTracker, ClouddriverApi clouddriverApi) { |
spinnaker/fiat | fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
| import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.*;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.val; | /*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.model.resources;
/**
* Representation of authorization configuration for a resource. This object is immutable, which
* makes it challenging when working with Jackson's {@code ObjectMapper} and Spring's
* {@code @ConfigurationProperties}. The {@link Builder} is a helper class for the latter use case.
*/
@ToString
@EqualsAndHashCode
public class Permissions {
public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.*;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.val;
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.model.resources;
/**
* Representation of authorization configuration for a resource. This object is immutable, which
* makes it challenging when working with Jackson's {@code ObjectMapper} and Spring's
* {@code @ConfigurationProperties}. The {@link Builder} is a helper class for the latter use case.
*/
@ToString
@EqualsAndHashCode
public class Permissions {
public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
| private final Map<Authorization, List<String>> permissions; |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class Front50Service {
private final Front50ApplicationLoader front50ApplicationLoader;
private final Front50ServiceAccountLoader front50ServiceAccountLoader;
public Front50Service(
Front50ApplicationLoader front50ApplicationLoader,
Front50ServiceAccountLoader front50ServiceAccountLoader) {
this.front50ApplicationLoader = front50ApplicationLoader;
this.front50ServiceAccountLoader = front50ServiceAccountLoader;
}
/** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
@Deprecated | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class Front50Service {
private final Front50ApplicationLoader front50ApplicationLoader;
private final Front50ServiceAccountLoader front50ServiceAccountLoader;
public Front50Service(
Front50ApplicationLoader front50ApplicationLoader,
Front50ServiceAccountLoader front50ServiceAccountLoader) {
this.front50ApplicationLoader = front50ApplicationLoader;
this.front50ServiceAccountLoader = front50ServiceAccountLoader;
}
/** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
@Deprecated | public List<Application> getAllApplications(boolean restricted) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class Front50Service {
private final Front50ApplicationLoader front50ApplicationLoader;
private final Front50ServiceAccountLoader front50ServiceAccountLoader;
public Front50Service(
Front50ApplicationLoader front50ApplicationLoader,
Front50ServiceAccountLoader front50ServiceAccountLoader) {
this.front50ApplicationLoader = front50ApplicationLoader;
this.front50ServiceAccountLoader = front50ServiceAccountLoader;
}
/** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
@Deprecated
public List<Application> getAllApplications(boolean restricted) {
return getAllApplications();
}
public List<Application> getAllApplications() {
return front50ApplicationLoader.getData();
}
| // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Service.java
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.providers.internal;
public class Front50Service {
private final Front50ApplicationLoader front50ApplicationLoader;
private final Front50ServiceAccountLoader front50ServiceAccountLoader;
public Front50Service(
Front50ApplicationLoader front50ApplicationLoader,
Front50ServiceAccountLoader front50ServiceAccountLoader) {
this.front50ApplicationLoader = front50ApplicationLoader;
this.front50ServiceAccountLoader = front50ServiceAccountLoader;
}
/** @deprecated use {@code getAllApplications} - the restricted parameter is ignored */
@Deprecated
public List<Application> getAllApplications(boolean restricted) {
return getAllApplications();
}
public List<Application> getAllApplications() {
return front50ApplicationLoader.getData();
}
| public List<ServiceAccount> getAllServiceAccounts() { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/AccessControlledResourcePermissionSource.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
// @ToString
// @EqualsAndHashCode
// public class Permissions {
//
// public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
//
// private final Map<Authorization, List<String>> permissions;
//
// private Permissions(Map<Authorization, List<String>> p) {
// this.permissions = Collections.unmodifiableMap(p);
// }
//
// /**
// * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
// * to sanitize the input data (just in case).
// */
// @JsonCreator
// public static Permissions factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data).build();
// }
//
// /** Here specifically for Jackson serialization. */
// @JsonValue
// private Map<Authorization, List<String>> getPermissions() {
// return permissions;
// }
//
// public Set<String> allGroups() {
// return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
// }
//
// /**
// * Determines whether this Permissions has any Authorizations with associated roles.
// *
// * @return whether this Permissions has any Authorizations with associated roles
// * @deprecated check {@code !isRestricted()} instead
// */
// @Deprecated
// public boolean isEmpty() {
// return !isRestricted();
// }
//
// public boolean isRestricted() {
// return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty());
// }
//
// public boolean isAuthorized(Set<Role> userRoles) {
// return !getAuthorizations(userRoles).isEmpty();
// }
//
// public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
// val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
// return getAuthorizations(r);
// }
//
// public Set<Authorization> getAuthorizations(List<String> userRoles) {
// if (!isRestricted()) {
// return Authorization.ALL;
// }
//
// return this.permissions.entrySet().stream()
// .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
// }
//
// public List<String> get(Authorization a) {
// return permissions.getOrDefault(a, new ArrayList<>());
// }
//
// public Map<Authorization, List<String>> unpack() {
// return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
// }
//
// /**
// * This is a helper class for setting up an immutable Permissions object. It also acts as the
// * target Java Object for Spring's ConfigurationProperties deserialization.
// *
// * <p>Objects should be defined on the account config like:
// *
// * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1
// *
// * <p>Group/Role names are trimmed of whitespace and lowercased.
// */
// public static class Builder extends LinkedHashMap<Authorization, List<String>> {
//
// private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
// final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
// for (Authorization auth : Authorization.values()) {
// Optional.ofNullable(authConfig.get(auth))
// .map(
// groups ->
// groups.stream()
// .map(String::trim)
// .filter(s -> !s.isEmpty())
// .map(String::toLowerCase)
// .collect(Collectors.toList()))
// .filter(g -> !g.isEmpty())
// .map(Collections::unmodifiableList)
// .ifPresent(roles -> perms.put(auth, roles));
// }
// return new Permissions(perms);
// }
//
// @JsonCreator
// public static Builder factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data);
// }
//
// public Builder set(Map<Authorization, List<String>> p) {
// this.clear();
// this.putAll(p);
// return this;
// }
//
// public Builder add(Authorization a, String group) {
// this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
// return this;
// }
//
// public Builder add(Authorization a, List<String> groups) {
// groups.forEach(group -> add(a, group));
// return this;
// }
//
// public Permissions build() {
// final Permissions result = fromMap(this);
// if (!result.isRestricted()) {
// return Permissions.EMPTY;
// }
// return result;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Permissions;
import com.netflix.spinnaker.fiat.model.resources.Resource;
import java.util.Optional;
import javax.annotation.Nonnull; | /*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
public final class AccessControlledResourcePermissionSource<T extends Resource.AccessControlled>
implements ResourcePermissionSource<T> {
@Override
@Nonnull | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Permissions.java
// @ToString
// @EqualsAndHashCode
// public class Permissions {
//
// public static final Permissions EMPTY = Builder.fromMap(Collections.emptyMap());
//
// private final Map<Authorization, List<String>> permissions;
//
// private Permissions(Map<Authorization, List<String>> p) {
// this.permissions = Collections.unmodifiableMap(p);
// }
//
// /**
// * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
// * to sanitize the input data (just in case).
// */
// @JsonCreator
// public static Permissions factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data).build();
// }
//
// /** Here specifically for Jackson serialization. */
// @JsonValue
// private Map<Authorization, List<String>> getPermissions() {
// return permissions;
// }
//
// public Set<String> allGroups() {
// return permissions.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
// }
//
// /**
// * Determines whether this Permissions has any Authorizations with associated roles.
// *
// * @return whether this Permissions has any Authorizations with associated roles
// * @deprecated check {@code !isRestricted()} instead
// */
// @Deprecated
// public boolean isEmpty() {
// return !isRestricted();
// }
//
// public boolean isRestricted() {
// return this.permissions.values().stream().anyMatch(groups -> !groups.isEmpty());
// }
//
// public boolean isAuthorized(Set<Role> userRoles) {
// return !getAuthorizations(userRoles).isEmpty();
// }
//
// public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
// val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
// return getAuthorizations(r);
// }
//
// public Set<Authorization> getAuthorizations(List<String> userRoles) {
// if (!isRestricted()) {
// return Authorization.ALL;
// }
//
// return this.permissions.entrySet().stream()
// .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
// .map(Map.Entry::getKey)
// .collect(Collectors.toSet());
// }
//
// public List<String> get(Authorization a) {
// return permissions.getOrDefault(a, new ArrayList<>());
// }
//
// public Map<Authorization, List<String>> unpack() {
// return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
// }
//
// /**
// * This is a helper class for setting up an immutable Permissions object. It also acts as the
// * target Java Object for Spring's ConfigurationProperties deserialization.
// *
// * <p>Objects should be defined on the account config like:
// *
// * <p>someRoot: name: resourceName permissions: read: - role1 - role2 write: - role1
// *
// * <p>Group/Role names are trimmed of whitespace and lowercased.
// */
// public static class Builder extends LinkedHashMap<Authorization, List<String>> {
//
// private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
// final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
// for (Authorization auth : Authorization.values()) {
// Optional.ofNullable(authConfig.get(auth))
// .map(
// groups ->
// groups.stream()
// .map(String::trim)
// .filter(s -> !s.isEmpty())
// .map(String::toLowerCase)
// .collect(Collectors.toList()))
// .filter(g -> !g.isEmpty())
// .map(Collections::unmodifiableList)
// .ifPresent(roles -> perms.put(auth, roles));
// }
// return new Permissions(perms);
// }
//
// @JsonCreator
// public static Builder factory(Map<Authorization, List<String>> data) {
// return new Builder().set(data);
// }
//
// public Builder set(Map<Authorization, List<String>> p) {
// this.clear();
// this.putAll(p);
// return this;
// }
//
// public Builder add(Authorization a, String group) {
// this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
// return this;
// }
//
// public Builder add(Authorization a, List<String> groups) {
// groups.forEach(group -> add(a, group));
// return this;
// }
//
// public Permissions build() {
// final Permissions result = fromMap(this);
// if (!result.isRestricted()) {
// return Permissions.EMPTY;
// }
// return result;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/AccessControlledResourcePermissionSource.java
import com.netflix.spinnaker.fiat.model.resources.Permissions;
import com.netflix.spinnaker.fiat.model.resources.Resource;
import java.util.Optional;
import javax.annotation.Nonnull;
/*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.providers;
public final class AccessControlledResourcePermissionSource<T extends Resource.AccessControlled>
implements ResourcePermissionSource<T> {
@Override
@Nonnull | public Permissions getPermissions(@Nonnull T resource) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Role;
import java.util.ArrayList;
import java.util.List;
import lombok.Data; | /*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.permissions;
/**
* ExternalUser is a model object for a user with roles assigned outside of the UserRoleProvider
* configured within Fiat. The most common scenario is a SAML authentication assertion that also
* includes role/group membership.
*/
@Data
public class ExternalUser {
private String id; | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Role.java
// @Component
// @Data
// @EqualsAndHashCode(of = "name")
// @NoArgsConstructor
// public class Role implements Resource, Viewable {
//
// private final ResourceType resourceType = ResourceType.ROLE;
// private String name;
//
// public enum Source {
// EXTERNAL,
// FILE,
// GOOGLE_GROUPS,
// GITHUB_TEAMS,
// LDAP
// }
//
// private Source source;
//
// public Role(String name) {
// this.setName(name);
// }
//
// public Role setName(@Nonnull String name) {
// if (!StringUtils.hasText(name)) {
// throw new IllegalArgumentException("name cannot be empty");
// }
// this.name = name.toLowerCase();
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private Source source;
//
// public View(Role role) {
// this.name = role.name;
// this.source = role.getSource();
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/permissions/ExternalUser.java
import com.netflix.spinnaker.fiat.model.resources.Role;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/*
* Copyright 2016 Google, 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 com.netflix.spinnaker.fiat.permissions;
/**
* ExternalUser is a model object for a user with roles assigned outside of the UserRoleProvider
* configured within Fiat. The most common scenario is a SAML authentication assertion that also
* includes role/group membership.
*/
@Data
public class ExternalUser {
private String id; | private List<Role> externalRoles = new ArrayList<>(); |
spinnaker/fiat | fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BaseAccessControlled.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
| import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.List;
import lombok.extern.slf4j.Slf4j; | * permissions.
*/
@SuppressWarnings("unchecked")
public <T extends BaseAccessControlled> T setRequiredGroupMembership(List<String> membership) {
if (membership == null || membership.isEmpty()) {
return (T) this;
}
if (getPermissions() != null && getPermissions().isRestricted()) {
String msg =
String.join(
" ",
"`requiredGroupMembership` found on",
getResourceType().toString(),
getName(),
"and ignored because `permissions` are present");
log.warn(msg);
return (T) this;
}
String msg =
String.join(
" ",
"Deprecated `requiredGroupMembership` found on",
getResourceType().toString(),
getName(),
". Please update to `permissions`.");
log.warn(msg);
this.setPermissions(
new Permissions.Builder() | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/Authorization.java
// public enum Authorization {
// READ,
// WRITE,
// EXECUTE,
// CREATE;
//
// public static final Set<Authorization> ALL =
// Collections.unmodifiableSet(EnumSet.allOf(Authorization.class));
// }
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/BaseAccessControlled.java
import com.netflix.spinnaker.fiat.model.Authorization;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
* permissions.
*/
@SuppressWarnings("unchecked")
public <T extends BaseAccessControlled> T setRequiredGroupMembership(List<String> membership) {
if (membership == null || membership.isEmpty()) {
return (T) this;
}
if (getPermissions() != null && getPermissions().isRestricted()) {
String msg =
String.join(
" ",
"`requiredGroupMembership` found on",
getResourceType().toString(),
getName(),
"and ignored because `permissions` are present");
log.warn(msg);
return (T) this;
}
String msg =
String.join(
" ",
"Deprecated `requiredGroupMembership` found on",
getResourceType().toString(),
getName(),
". Please update to `permissions`.");
log.warn(msg);
this.setPermissions(
new Permissions.Builder() | .add(Authorization.READ, membership) |
spinnaker/fiat | fiat-github/src/main/java/com/netflix/spinnaker/fiat/config/GitHubConfig.java | // Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/GitHubProperties.java
// @Configuration
// @ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
// @ConfigurationProperties(prefix = "auth.group-membership.github")
// @Data
// public class GitHubProperties {
// @NotEmpty private String baseUrl;
// @NotEmpty private String accessToken;
// @NotEmpty private String organization;
//
// @NotNull
// @Max(100L)
// @Min(1L)
// Integer paginationValue = 100;
//
// @NotNull Integer membershipCacheTTLSeconds = 60 * 10; // 10 min time to refresh
// @NotNull Integer membershipCacheTeamsSize = 1000; // 1000 github teams
// }
//
// Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/client/GitHubClient.java
// public interface GitHubClient {
//
// @GET("/orgs/{org}/members/{username}")
// Response isMemberOfOrganization(@Path("org") String org, @Path("username") String username);
//
// /** This one should use the Current User credentials */
// @GET("/user/teams")
// List<Team> getUserTeams();
//
// @GET("/orgs/{org}/teams")
// List<Team> getOrgTeams(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/orgs/{org}/members")
// List<Member> getOrgMembers(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/members")
// List<Member> getMembersOfTeam(
// @Path("idTeam") Long idTeam, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/memberships/{username}")
// TeamMembership isMemberOfTeam(@Path("idTeam") Long idTeam, @Path("username") String username);
// }
| import com.jakewharton.retrofit.Ok3Client;
import com.netflix.spinnaker.config.DefaultServiceEndpoint;
import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.fiat.roles.github.GitHubProperties;
import com.netflix.spinnaker.fiat.roles.github.client.GitHubClient;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.Endpoints;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter; | package com.netflix.spinnaker.fiat.config;
/**
* Converts the list of GitHub Configuration properties a collection of clients to access the GitHub
* hosts
*/
@Configuration
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
@Slf4j
public class GitHubConfig {
@Autowired @Setter private RestAdapter.LogLevel retrofitLogLevel;
| // Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/GitHubProperties.java
// @Configuration
// @ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
// @ConfigurationProperties(prefix = "auth.group-membership.github")
// @Data
// public class GitHubProperties {
// @NotEmpty private String baseUrl;
// @NotEmpty private String accessToken;
// @NotEmpty private String organization;
//
// @NotNull
// @Max(100L)
// @Min(1L)
// Integer paginationValue = 100;
//
// @NotNull Integer membershipCacheTTLSeconds = 60 * 10; // 10 min time to refresh
// @NotNull Integer membershipCacheTeamsSize = 1000; // 1000 github teams
// }
//
// Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/client/GitHubClient.java
// public interface GitHubClient {
//
// @GET("/orgs/{org}/members/{username}")
// Response isMemberOfOrganization(@Path("org") String org, @Path("username") String username);
//
// /** This one should use the Current User credentials */
// @GET("/user/teams")
// List<Team> getUserTeams();
//
// @GET("/orgs/{org}/teams")
// List<Team> getOrgTeams(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/orgs/{org}/members")
// List<Member> getOrgMembers(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/members")
// List<Member> getMembersOfTeam(
// @Path("idTeam") Long idTeam, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/memberships/{username}")
// TeamMembership isMemberOfTeam(@Path("idTeam") Long idTeam, @Path("username") String username);
// }
// Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/config/GitHubConfig.java
import com.jakewharton.retrofit.Ok3Client;
import com.netflix.spinnaker.config.DefaultServiceEndpoint;
import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.fiat.roles.github.GitHubProperties;
import com.netflix.spinnaker.fiat.roles.github.client.GitHubClient;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.Endpoints;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter;
package com.netflix.spinnaker.fiat.config;
/**
* Converts the list of GitHub Configuration properties a collection of clients to access the GitHub
* hosts
*/
@Configuration
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
@Slf4j
public class GitHubConfig {
@Autowired @Setter private RestAdapter.LogLevel retrofitLogLevel;
| @Autowired @Setter private GitHubProperties gitHubProperties; |
spinnaker/fiat | fiat-github/src/main/java/com/netflix/spinnaker/fiat/config/GitHubConfig.java | // Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/GitHubProperties.java
// @Configuration
// @ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
// @ConfigurationProperties(prefix = "auth.group-membership.github")
// @Data
// public class GitHubProperties {
// @NotEmpty private String baseUrl;
// @NotEmpty private String accessToken;
// @NotEmpty private String organization;
//
// @NotNull
// @Max(100L)
// @Min(1L)
// Integer paginationValue = 100;
//
// @NotNull Integer membershipCacheTTLSeconds = 60 * 10; // 10 min time to refresh
// @NotNull Integer membershipCacheTeamsSize = 1000; // 1000 github teams
// }
//
// Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/client/GitHubClient.java
// public interface GitHubClient {
//
// @GET("/orgs/{org}/members/{username}")
// Response isMemberOfOrganization(@Path("org") String org, @Path("username") String username);
//
// /** This one should use the Current User credentials */
// @GET("/user/teams")
// List<Team> getUserTeams();
//
// @GET("/orgs/{org}/teams")
// List<Team> getOrgTeams(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/orgs/{org}/members")
// List<Member> getOrgMembers(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/members")
// List<Member> getMembersOfTeam(
// @Path("idTeam") Long idTeam, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/memberships/{username}")
// TeamMembership isMemberOfTeam(@Path("idTeam") Long idTeam, @Path("username") String username);
// }
| import com.jakewharton.retrofit.Ok3Client;
import com.netflix.spinnaker.config.DefaultServiceEndpoint;
import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.fiat.roles.github.GitHubProperties;
import com.netflix.spinnaker.fiat.roles.github.client.GitHubClient;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.Endpoints;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter; | package com.netflix.spinnaker.fiat.config;
/**
* Converts the list of GitHub Configuration properties a collection of clients to access the GitHub
* hosts
*/
@Configuration
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
@Slf4j
public class GitHubConfig {
@Autowired @Setter private RestAdapter.LogLevel retrofitLogLevel;
@Autowired @Setter private GitHubProperties gitHubProperties;
@Bean | // Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/GitHubProperties.java
// @Configuration
// @ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
// @ConfigurationProperties(prefix = "auth.group-membership.github")
// @Data
// public class GitHubProperties {
// @NotEmpty private String baseUrl;
// @NotEmpty private String accessToken;
// @NotEmpty private String organization;
//
// @NotNull
// @Max(100L)
// @Min(1L)
// Integer paginationValue = 100;
//
// @NotNull Integer membershipCacheTTLSeconds = 60 * 10; // 10 min time to refresh
// @NotNull Integer membershipCacheTeamsSize = 1000; // 1000 github teams
// }
//
// Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/roles/github/client/GitHubClient.java
// public interface GitHubClient {
//
// @GET("/orgs/{org}/members/{username}")
// Response isMemberOfOrganization(@Path("org") String org, @Path("username") String username);
//
// /** This one should use the Current User credentials */
// @GET("/user/teams")
// List<Team> getUserTeams();
//
// @GET("/orgs/{org}/teams")
// List<Team> getOrgTeams(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/orgs/{org}/members")
// List<Member> getOrgMembers(
// @Path("org") String org, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/members")
// List<Member> getMembersOfTeam(
// @Path("idTeam") Long idTeam, @Query("page") int page, @Query("per_page") int paginationValue);
//
// @GET("/teams/{idTeam}/memberships/{username}")
// TeamMembership isMemberOfTeam(@Path("idTeam") Long idTeam, @Path("username") String username);
// }
// Path: fiat-github/src/main/java/com/netflix/spinnaker/fiat/config/GitHubConfig.java
import com.jakewharton.retrofit.Ok3Client;
import com.netflix.spinnaker.config.DefaultServiceEndpoint;
import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.fiat.roles.github.GitHubProperties;
import com.netflix.spinnaker.fiat.roles.github.client.GitHubClient;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.Endpoints;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter;
package com.netflix.spinnaker.fiat.config;
/**
* Converts the list of GitHub Configuration properties a collection of clients to access the GitHub
* hosts
*/
@Configuration
@ConditionalOnProperty(value = "auth.group-membership.service", havingValue = "github")
@Slf4j
public class GitHubConfig {
@Autowired @Setter private RestAdapter.LogLevel retrofitLogLevel;
@Autowired @Setter private GitHubProperties gitHubProperties;
@Bean | public GitHubClient gitHubClient(OkHttpClientProvider clientProvider) { |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Api.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Query; | /*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface Front50Api {
@GET("/permissions/applications") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Api.java
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Query;
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface Front50Api {
@GET("/permissions/applications") | List<Application> getAllApplicationPermissions(); |
spinnaker/fiat | fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Api.java | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
| import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Query; | /*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface Front50Api {
@GET("/permissions/applications")
List<Application> getAllApplicationPermissions();
/**
* @deprecated for fiat's usage this is always going to be called with restricted = false, use the
* no arg method instead which has the same behavior.
*/
@GET("/v2/applications")
@Deprecated
List<Application> getAllApplications(@Query("restricted") boolean restricted);
@GET("/v2/applications?restricted=false")
List<Application> getAllApplications();
@GET("/serviceAccounts") | // Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/Application.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Application extends BaseAccessControlled<Application> implements Viewable {
// final ResourceType resourceType = ResourceType.APPLICATION;
//
// private String name;
// private Permissions permissions = Permissions.EMPTY;
//
// private Map<String, Object> details = new HashMap<>();
//
// @JsonAnySetter
// public void setDetails(String name, Object value) {
// this.details.put(name, value);
// }
//
// @JsonIgnore
// public View getView(Set<Role> userRoles, boolean isAdmin) {
// return new View(this, userRoles, isAdmin);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView implements Authorizable {
// String name;
// Set<Authorization> authorizations;
//
// public View(Application application, Set<Role> userRoles, boolean isAdmin) {
// this.name = application.name;
// if (isAdmin) {
// this.authorizations = Authorization.ALL;
// } else {
// this.authorizations = application.permissions.getAuthorizations(userRoles);
// }
// }
// }
// }
//
// Path: fiat-core/src/main/java/com/netflix/spinnaker/fiat/model/resources/ServiceAccount.java
// @Component
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class ServiceAccount implements Resource, Viewable {
// private final ResourceType resourceType = ResourceType.SERVICE_ACCOUNT;
//
// private String name;
// private List<String> memberOf = new ArrayList<>();
//
// public UserPermission toUserPermission() {
// val roles =
// memberOf.stream()
// .filter(StringUtils::hasText)
// .map(membership -> new Role(membership).setSource(Role.Source.EXTERNAL))
// .collect(Collectors.toSet());
// return new UserPermission().setId(name).setRoles(roles);
// }
//
// public ServiceAccount setMemberOf(List<String> membership) {
// if (membership == null) {
// membership = new ArrayList<>();
// }
// memberOf =
// membership.stream().map(String::trim).map(String::toLowerCase).collect(Collectors.toList());
// return this;
// }
//
// @JsonIgnore
// @Override
// public View getView(Set<Role> ignored, boolean isAdmin) {
// return new View(this);
// }
//
// @Data
// @EqualsAndHashCode(callSuper = false)
// @NoArgsConstructor
// public static class View extends BaseView {
// private String name;
// private List<String> memberOf;
//
// public View(ServiceAccount serviceAccount) {
// this.name = serviceAccount.name;
// this.memberOf = serviceAccount.memberOf;
// }
// }
// }
// Path: fiat-roles/src/main/java/com/netflix/spinnaker/fiat/providers/internal/Front50Api.java
import com.netflix.spinnaker.fiat.model.resources.Application;
import com.netflix.spinnaker.fiat.model.resources.ServiceAccount;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Query;
/*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.fiat.providers.internal;
public interface Front50Api {
@GET("/permissions/applications")
List<Application> getAllApplicationPermissions();
/**
* @deprecated for fiat's usage this is always going to be called with restricted = false, use the
* no arg method instead which has the same behavior.
*/
@GET("/v2/applications")
@Deprecated
List<Application> getAllApplications(@Query("restricted") boolean restricted);
@GET("/v2/applications?restricted=false")
List<Application> getAllApplications();
@GET("/serviceAccounts") | List<ServiceAccount> getAllServiceAccounts(); |
assist-group/assist-mcommerce-sdk-android | TestAssistSDK/src/main/java/ru/assisttech/assistsdk/ViewResultActivity.java | // Path: sdk/src/main/java/ru/assisttech/sdk/storage/AssistTransaction.java
// public class AssistTransaction {
//
// public static final int UNREGISTERED_ID = -1;
// private long id;
// private String merchantID;
// private String orderDateUTC;
// private String orderDateDevice;
// private String orderNumber;
// private String orderComment;
// private String orderAmount;
// private Currency orderCurrency;
// private PaymentMethod paymentMethod;
// private boolean requireUserSignature;
// private byte[] userSignature;
// private AssistResult result;
// private List<AssistOrderItem> orderItems;
//
// public enum PaymentMethod {
// CARD_MANUAL,
// CARD_PHOTO_SCAN,
// CARD_TERMINAL,
// CASH
// }
//
// public AssistTransaction() {
// result = new AssistResult(AssistResult.OrderState.UNKNOWN);
// id = UNREGISTERED_ID;
// }
//
// public boolean isStored() {
// return id != UNREGISTERED_ID;
// }
//
// public long getId() {
// return id;
// }
//
// public String getMerchantID() {
// return merchantID;
// }
//
// public String getOrderDateUTC() {
// return orderDateUTC;
// }
//
// public String getOrderDateDevice() {
// return orderDateDevice;
// }
//
// public String getOrderNumber() {
// return orderNumber;
// }
//
// public String getOrderComment() {
// return orderComment;
// }
//
// public String getOrderAmount() {
// return orderAmount;
// }
//
// public Currency getOrderCurrency() {
// return orderCurrency;
// }
//
// public PaymentMethod getPaymentMethod() {
// return paymentMethod;
// }
//
// public boolean isRequireUserSignature() {
// return requireUserSignature;
// }
//
// public byte[] getUserSignature() {
// return userSignature;
// }
//
// public AssistResult getResult() {
// return result;
// }
//
// public boolean hasOrderItems() {
// return orderItems != null;
// }
//
// public List<AssistOrderItem> getOrderItems() {
// return orderItems;
// }
//
// public void setId(long value) {
// id = value;
// }
//
// public void setMerchantID(String value) {
// merchantID = value;
// }
//
// public void setOrderDateUTC(String value) {
// orderDateUTC = value;
// }
//
// public void setOrderDateDevice(String value) {
// orderDateDevice = value;
// }
//
// public void setOrderNumber(String value) {
// orderNumber = value;
// }
//
// public void setOrderComment(String value) {
// orderComment = value;
// }
//
// public void setOrderAmount(String value) {
// orderAmount = value;
// if (orderAmount != null) {
// if (orderAmount.contains(",")) {
// orderAmount = orderAmount.replace(",", ".");
// }
// orderAmount = formatAmount(orderAmount);
// }
// }
//
// public void setOrderCurrency(Currency value) {
// orderCurrency = value;
// }
//
// public void setPaymentMethod(PaymentMethod value) {
// paymentMethod = value;
// }
//
// public void setRequireUserSignature(boolean value) {
// requireUserSignature = value;
// }
//
// public void setUserSignature(byte[] value) {
// userSignature = value;
// }
//
// public void setResult(AssistResult value) {
// result = value;
// }
//
// public void setOrderItems(List<AssistOrderItem> items) {
// orderItems = items;
// }
//
// public static String formatAmount(String amount) {
// if (TextUtils.isEmpty(amount))
// return amount;
//
// String outAmount;
// int diff = -1;
// if (amount.contains(".")) {
// diff = amount.length() - 1 - amount.indexOf(".");
// } else if (amount.contains(",")) {
// diff = amount.length() - 1 - amount.indexOf(",");
// }
// switch (diff) {
// case 0:
// outAmount = amount.concat("00");
// break;
// case 1:
// outAmount = amount.concat("0");
// break;
// default:
// outAmount = amount;
// break;
// }
// return outAmount;
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import ru.assisttech.sdk.storage.AssistTransaction; | package ru.assisttech.assistsdk;
public class ViewResultActivity extends Activity {
public static final String TRANSACTION_ID_EXTRA = "transaction_id_extra";
private long transactionID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
transactionID = getIntent().getLongExtra(TRANSACTION_ID_EXTRA, -1);
initUI();
}
@Override
public void onBackPressed() {
toMainScreen();
}
private void initUI() {
TextView tvResultOrderNumber = (TextView) findViewById(R.id.tvResultOrderNumber);
TextView tvResultOrderComment = (TextView) findViewById(R.id.tvResultOrderComment);
TextView tvResultOrderAmount = (TextView) findViewById(R.id.tvResultOrderAmount);
TextView tvResultStatus = (TextView) findViewById(R.id.tvResultStatus);
TextView tvResultInfo = (TextView) findViewById(R.id.tvResultExtraInfo);
ApplicationConfiguration cfg = ApplicationConfiguration.getInstance(); | // Path: sdk/src/main/java/ru/assisttech/sdk/storage/AssistTransaction.java
// public class AssistTransaction {
//
// public static final int UNREGISTERED_ID = -1;
// private long id;
// private String merchantID;
// private String orderDateUTC;
// private String orderDateDevice;
// private String orderNumber;
// private String orderComment;
// private String orderAmount;
// private Currency orderCurrency;
// private PaymentMethod paymentMethod;
// private boolean requireUserSignature;
// private byte[] userSignature;
// private AssistResult result;
// private List<AssistOrderItem> orderItems;
//
// public enum PaymentMethod {
// CARD_MANUAL,
// CARD_PHOTO_SCAN,
// CARD_TERMINAL,
// CASH
// }
//
// public AssistTransaction() {
// result = new AssistResult(AssistResult.OrderState.UNKNOWN);
// id = UNREGISTERED_ID;
// }
//
// public boolean isStored() {
// return id != UNREGISTERED_ID;
// }
//
// public long getId() {
// return id;
// }
//
// public String getMerchantID() {
// return merchantID;
// }
//
// public String getOrderDateUTC() {
// return orderDateUTC;
// }
//
// public String getOrderDateDevice() {
// return orderDateDevice;
// }
//
// public String getOrderNumber() {
// return orderNumber;
// }
//
// public String getOrderComment() {
// return orderComment;
// }
//
// public String getOrderAmount() {
// return orderAmount;
// }
//
// public Currency getOrderCurrency() {
// return orderCurrency;
// }
//
// public PaymentMethod getPaymentMethod() {
// return paymentMethod;
// }
//
// public boolean isRequireUserSignature() {
// return requireUserSignature;
// }
//
// public byte[] getUserSignature() {
// return userSignature;
// }
//
// public AssistResult getResult() {
// return result;
// }
//
// public boolean hasOrderItems() {
// return orderItems != null;
// }
//
// public List<AssistOrderItem> getOrderItems() {
// return orderItems;
// }
//
// public void setId(long value) {
// id = value;
// }
//
// public void setMerchantID(String value) {
// merchantID = value;
// }
//
// public void setOrderDateUTC(String value) {
// orderDateUTC = value;
// }
//
// public void setOrderDateDevice(String value) {
// orderDateDevice = value;
// }
//
// public void setOrderNumber(String value) {
// orderNumber = value;
// }
//
// public void setOrderComment(String value) {
// orderComment = value;
// }
//
// public void setOrderAmount(String value) {
// orderAmount = value;
// if (orderAmount != null) {
// if (orderAmount.contains(",")) {
// orderAmount = orderAmount.replace(",", ".");
// }
// orderAmount = formatAmount(orderAmount);
// }
// }
//
// public void setOrderCurrency(Currency value) {
// orderCurrency = value;
// }
//
// public void setPaymentMethod(PaymentMethod value) {
// paymentMethod = value;
// }
//
// public void setRequireUserSignature(boolean value) {
// requireUserSignature = value;
// }
//
// public void setUserSignature(byte[] value) {
// userSignature = value;
// }
//
// public void setResult(AssistResult value) {
// result = value;
// }
//
// public void setOrderItems(List<AssistOrderItem> items) {
// orderItems = items;
// }
//
// public static String formatAmount(String amount) {
// if (TextUtils.isEmpty(amount))
// return amount;
//
// String outAmount;
// int diff = -1;
// if (amount.contains(".")) {
// diff = amount.length() - 1 - amount.indexOf(".");
// } else if (amount.contains(",")) {
// diff = amount.length() - 1 - amount.indexOf(",");
// }
// switch (diff) {
// case 0:
// outAmount = amount.concat("00");
// break;
// case 1:
// outAmount = amount.concat("0");
// break;
// default:
// outAmount = amount;
// break;
// }
// return outAmount;
// }
// }
// Path: TestAssistSDK/src/main/java/ru/assisttech/assistsdk/ViewResultActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import ru.assisttech.sdk.storage.AssistTransaction;
package ru.assisttech.assistsdk;
public class ViewResultActivity extends Activity {
public static final String TRANSACTION_ID_EXTRA = "transaction_id_extra";
private long transactionID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
transactionID = getIntent().getLongExtra(TRANSACTION_ID_EXTRA, -1);
initUI();
}
@Override
public void onBackPressed() {
toMainScreen();
}
private void initUI() {
TextView tvResultOrderNumber = (TextView) findViewById(R.id.tvResultOrderNumber);
TextView tvResultOrderComment = (TextView) findViewById(R.id.tvResultOrderComment);
TextView tvResultOrderAmount = (TextView) findViewById(R.id.tvResultOrderAmount);
TextView tvResultStatus = (TextView) findViewById(R.id.tvResultStatus);
TextView tvResultInfo = (TextView) findViewById(R.id.tvResultExtraInfo);
ApplicationConfiguration cfg = ApplicationConfiguration.getInstance(); | AssistTransaction transaction = cfg.getPaymentEngine().transactionStorage().getTransaction(transactionID); |
assist-group/assist-mcommerce-sdk-android | TestAssistSDK/src/main/java/ru/assisttech/assistsdk/AboutActivity.java | // Path: sdk/src/main/java/ru/assisttech/sdk/AssistSDK.java
// public class AssistSDK {
//
// public static AssistPayEngine getPayEngine(Activity activity) {
// return AssistPayEngine.getInstance(activity.getApplicationContext());
// }
//
// public static String getSdkVersion() {
// return BuildConfig.VERSION_NAME;
// }
// }
| import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import ru.assisttech.sdk.AssistSDK; | package ru.assisttech.assistsdk;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
if (getActionBar() != null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
TextView tvVersion = (TextView)findViewById(R.id.tvAppVersion);
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
tvVersion.setText(String.format(getString(R.string.app_version), pInfo.versionName));
} catch (PackageManager.NameNotFoundException e) {
tvVersion.setText(String.format(getString(R.string.app_version), "unknown"));
e.printStackTrace();
}
TextView tvSDKVersion = (TextView)findViewById(R.id.tvSDKVersion); | // Path: sdk/src/main/java/ru/assisttech/sdk/AssistSDK.java
// public class AssistSDK {
//
// public static AssistPayEngine getPayEngine(Activity activity) {
// return AssistPayEngine.getInstance(activity.getApplicationContext());
// }
//
// public static String getSdkVersion() {
// return BuildConfig.VERSION_NAME;
// }
// }
// Path: TestAssistSDK/src/main/java/ru/assisttech/assistsdk/AboutActivity.java
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import ru.assisttech.sdk.AssistSDK;
package ru.assisttech.assistsdk;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
if (getActionBar() != null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
TextView tvVersion = (TextView)findViewById(R.id.tvAppVersion);
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
tvVersion.setText(String.format(getString(R.string.app_version), pInfo.versionName));
} catch (PackageManager.NameNotFoundException e) {
tvVersion.setText(String.format(getString(R.string.app_version), "unknown"));
e.printStackTrace();
}
TextView tvSDKVersion = (TextView)findViewById(R.id.tvSDKVersion); | tvSDKVersion.setText(String.format(getString(R.string.sdk_version), AssistSDK.getSdkVersion())); |
android/car-samples | car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/navigation/NavigationNotificationService.java | // Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public final class ShowcaseService extends CarAppService {
// public static final String SHARED_PREF_KEY = "ShowcasePrefs";
// public static final String PRE_SEED_KEY = "PreSeed";
//
// // Intent actions for notification actions in car and phone
// public static final String INTENT_ACTION_NAVIGATE =
// "androidx.car.app.sample.showcase.INTENT_ACTION_PHONE";
// public static final String INTENT_ACTION_CALL =
// "androidx.car.app.sample.showcase.INTENT_ACTION_CANCEL_RESERVATION";
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// /** Creates a deep link URI with the given deep link action. */
// @NonNull
// public static Uri createDeepLinkUri(@NonNull String deepLinkAction) {
// return Uri.fromParts(ShowcaseSession.URI_SCHEME, ShowcaseSession.URI_HOST, deepLinkAction);
// }
//
// @Override
// @NonNull
// public Session onCreateSession() {
// return new ShowcaseSession();
// }
//
// @NonNull
// @Override
// public HostValidator createHostValidator() {
// if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
// } else {
// return new HostValidator.Builder(getApplicationContext())
// .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample)
// .build();
// }
// }
// }
| import static androidx.car.app.sample.showcase.common.ShowcaseService.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.car.app.notification.CarAppExtender;
import androidx.car.app.notification.CarNotificationManager;
import androidx.car.app.notification.CarPendingIntent;
import androidx.car.app.sample.showcase.common.R;
import androidx.car.app.sample.showcase.common.ShowcaseService;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.math.RoundingMode;
import java.text.DecimalFormat; | /**
* Initializes the notifications, if needed.
*
* <p>{@link NotificationManager#IMPORTANCE_HIGH} is needed to show the alerts on top of the car
* screen. However, the rail widget at the bottom of the screen will show regardless of the
* importance setting.
*/
// Suppressing 'ObsoleteSdkInt' as this code is shared between APKs with different min SDK
// levels
@SuppressLint({"ObsoleteSdkInt"})
private static void initNotifications(Context context) {
NotificationChannelCompat navChannel =
new NotificationChannelCompat.Builder(
NAV_NOTIFICATION_CHANNEL_ID,
NotificationManagerCompat.IMPORTANCE_HIGH)
.setName(NAV_NOTIFICATION_CHANNEL_NAME).build();
CarNotificationManager.from(context).createNotificationChannel(navChannel);
}
/** Returns the navigation notification that corresponds to the given notification count. */
static NotificationCompat.Builder getNavigationNotification(
Context context, int notificationCount) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, NAV_NOTIFICATION_CHANNEL_ID);
DirectionInfo directionInfo = getDirectionInfo(notificationCount);
// Set an intent to open the car app. The app receives this intent when the user taps the
// heads-up notification or the rail widget.
PendingIntent pendingIntent = CarPendingIntent.getCarApp(
context, | // Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public final class ShowcaseService extends CarAppService {
// public static final String SHARED_PREF_KEY = "ShowcasePrefs";
// public static final String PRE_SEED_KEY = "PreSeed";
//
// // Intent actions for notification actions in car and phone
// public static final String INTENT_ACTION_NAVIGATE =
// "androidx.car.app.sample.showcase.INTENT_ACTION_PHONE";
// public static final String INTENT_ACTION_CALL =
// "androidx.car.app.sample.showcase.INTENT_ACTION_CANCEL_RESERVATION";
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// /** Creates a deep link URI with the given deep link action. */
// @NonNull
// public static Uri createDeepLinkUri(@NonNull String deepLinkAction) {
// return Uri.fromParts(ShowcaseSession.URI_SCHEME, ShowcaseSession.URI_HOST, deepLinkAction);
// }
//
// @Override
// @NonNull
// public Session onCreateSession() {
// return new ShowcaseSession();
// }
//
// @NonNull
// @Override
// public HostValidator createHostValidator() {
// if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
// } else {
// return new HostValidator.Builder(getApplicationContext())
// .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample)
// .build();
// }
// }
// }
// Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/navigation/NavigationNotificationService.java
import static androidx.car.app.sample.showcase.common.ShowcaseService.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.car.app.notification.CarAppExtender;
import androidx.car.app.notification.CarNotificationManager;
import androidx.car.app.notification.CarPendingIntent;
import androidx.car.app.sample.showcase.common.R;
import androidx.car.app.sample.showcase.common.ShowcaseService;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.math.RoundingMode;
import java.text.DecimalFormat;
/**
* Initializes the notifications, if needed.
*
* <p>{@link NotificationManager#IMPORTANCE_HIGH} is needed to show the alerts on top of the car
* screen. However, the rail widget at the bottom of the screen will show regardless of the
* importance setting.
*/
// Suppressing 'ObsoleteSdkInt' as this code is shared between APKs with different min SDK
// levels
@SuppressLint({"ObsoleteSdkInt"})
private static void initNotifications(Context context) {
NotificationChannelCompat navChannel =
new NotificationChannelCompat.Builder(
NAV_NOTIFICATION_CHANNEL_ID,
NotificationManagerCompat.IMPORTANCE_HIGH)
.setName(NAV_NOTIFICATION_CHANNEL_NAME).build();
CarNotificationManager.from(context).createNotificationChannel(navChannel);
}
/** Returns the navigation notification that corresponds to the given notification count. */
static NotificationCompat.Builder getNavigationNotification(
Context context, int notificationCount) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, NAV_NOTIFICATION_CHANNEL_ID);
DirectionInfo directionInfo = getDirectionInfo(notificationCount);
// Set an intent to open the car app. The app receives this intent when the user taps the
// heads-up notification or the rail widget.
PendingIntent pendingIntent = CarPendingIntent.getCarApp(
context, | INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP.hashCode(), |
android/car-samples | car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/navigation/NavigationNotificationService.java | // Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public final class ShowcaseService extends CarAppService {
// public static final String SHARED_PREF_KEY = "ShowcasePrefs";
// public static final String PRE_SEED_KEY = "PreSeed";
//
// // Intent actions for notification actions in car and phone
// public static final String INTENT_ACTION_NAVIGATE =
// "androidx.car.app.sample.showcase.INTENT_ACTION_PHONE";
// public static final String INTENT_ACTION_CALL =
// "androidx.car.app.sample.showcase.INTENT_ACTION_CANCEL_RESERVATION";
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// /** Creates a deep link URI with the given deep link action. */
// @NonNull
// public static Uri createDeepLinkUri(@NonNull String deepLinkAction) {
// return Uri.fromParts(ShowcaseSession.URI_SCHEME, ShowcaseSession.URI_HOST, deepLinkAction);
// }
//
// @Override
// @NonNull
// public Session onCreateSession() {
// return new ShowcaseSession();
// }
//
// @NonNull
// @Override
// public HostValidator createHostValidator() {
// if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
// } else {
// return new HostValidator.Builder(getApplicationContext())
// .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample)
// .build();
// }
// }
// }
| import static androidx.car.app.sample.showcase.common.ShowcaseService.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.car.app.notification.CarAppExtender;
import androidx.car.app.notification.CarNotificationManager;
import androidx.car.app.notification.CarPendingIntent;
import androidx.car.app.sample.showcase.common.R;
import androidx.car.app.sample.showcase.common.ShowcaseService;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.math.RoundingMode;
import java.text.DecimalFormat; | * screen. However, the rail widget at the bottom of the screen will show regardless of the
* importance setting.
*/
// Suppressing 'ObsoleteSdkInt' as this code is shared between APKs with different min SDK
// levels
@SuppressLint({"ObsoleteSdkInt"})
private static void initNotifications(Context context) {
NotificationChannelCompat navChannel =
new NotificationChannelCompat.Builder(
NAV_NOTIFICATION_CHANNEL_ID,
NotificationManagerCompat.IMPORTANCE_HIGH)
.setName(NAV_NOTIFICATION_CHANNEL_NAME).build();
CarNotificationManager.from(context).createNotificationChannel(navChannel);
}
/** Returns the navigation notification that corresponds to the given notification count. */
static NotificationCompat.Builder getNavigationNotification(
Context context, int notificationCount) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, NAV_NOTIFICATION_CHANNEL_ID);
DirectionInfo directionInfo = getDirectionInfo(notificationCount);
// Set an intent to open the car app. The app receives this intent when the user taps the
// heads-up notification or the rail widget.
PendingIntent pendingIntent = CarPendingIntent.getCarApp(
context,
INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP.hashCode(),
new Intent(
INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP).setComponent(
new ComponentName(context, | // Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/ShowcaseService.java
// public final class ShowcaseService extends CarAppService {
// public static final String SHARED_PREF_KEY = "ShowcasePrefs";
// public static final String PRE_SEED_KEY = "PreSeed";
//
// // Intent actions for notification actions in car and phone
// public static final String INTENT_ACTION_NAVIGATE =
// "androidx.car.app.sample.showcase.INTENT_ACTION_PHONE";
// public static final String INTENT_ACTION_CALL =
// "androidx.car.app.sample.showcase.INTENT_ACTION_CANCEL_RESERVATION";
// public static final String INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP =
// "androidx.car.app.sample.showcase.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP";
//
// /** Creates a deep link URI with the given deep link action. */
// @NonNull
// public static Uri createDeepLinkUri(@NonNull String deepLinkAction) {
// return Uri.fromParts(ShowcaseSession.URI_SCHEME, ShowcaseSession.URI_HOST, deepLinkAction);
// }
//
// @Override
// @NonNull
// public Session onCreateSession() {
// return new ShowcaseSession();
// }
//
// @NonNull
// @Override
// public HostValidator createHostValidator() {
// if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
// } else {
// return new HostValidator.Builder(getApplicationContext())
// .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample)
// .build();
// }
// }
// }
// Path: car_app_library/showcase/common/src/main/java/androidx/car/app/sample/showcase/common/navigation/NavigationNotificationService.java
import static androidx.car.app.sample.showcase.common.ShowcaseService.INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.car.app.notification.CarAppExtender;
import androidx.car.app.notification.CarNotificationManager;
import androidx.car.app.notification.CarPendingIntent;
import androidx.car.app.sample.showcase.common.R;
import androidx.car.app.sample.showcase.common.ShowcaseService;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.math.RoundingMode;
import java.text.DecimalFormat;
* screen. However, the rail widget at the bottom of the screen will show regardless of the
* importance setting.
*/
// Suppressing 'ObsoleteSdkInt' as this code is shared between APKs with different min SDK
// levels
@SuppressLint({"ObsoleteSdkInt"})
private static void initNotifications(Context context) {
NotificationChannelCompat navChannel =
new NotificationChannelCompat.Builder(
NAV_NOTIFICATION_CHANNEL_ID,
NotificationManagerCompat.IMPORTANCE_HIGH)
.setName(NAV_NOTIFICATION_CHANNEL_NAME).build();
CarNotificationManager.from(context).createNotificationChannel(navChannel);
}
/** Returns the navigation notification that corresponds to the given notification count. */
static NotificationCompat.Builder getNavigationNotification(
Context context, int notificationCount) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, NAV_NOTIFICATION_CHANNEL_ID);
DirectionInfo directionInfo = getDirectionInfo(notificationCount);
// Set an intent to open the car app. The app receives this intent when the user taps the
// heads-up notification or the rail widget.
PendingIntent pendingIntent = CarPendingIntent.getCarApp(
context,
INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP.hashCode(),
new Intent(
INTENT_ACTION_NAV_NOTIFICATION_OPEN_APP).setComponent(
new ComponentName(context, | ShowcaseService.class)).setData( |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/editor/actions/NewOutlineSameLevel.java | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
| import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl; | }
return candidate;
}
private PsiElement findNextOutline(PsiElement element) {
PsiElement candidate = findRootLevel(element);
while(candidate != null && !isOutlineBlock(candidate)) {
candidate = candidate.getNextSibling();
}
return candidate;
}
private int outlineDepth(final PsiElement element) {
if(isOutlineBlock(element)) {
return element.getText().split("\\s")[0].length();
}
final PsiElement previousOutline = findPreviousOutline(element);
return previousOutline == null? 0 : outlineDepth(previousOutline);
}
private String createOutlineSameDepthAs(PsiElement currentOutline) {
return currentOutline.getText().split("\\s")[0] + " ";
}
private PsiElement findPreviousOutline(PsiElement element) {
PsiElement candidate = findRootLevel(element);
while (candidate != null && | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/editor/actions/NewOutlineSameLevel.java
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
}
return candidate;
}
private PsiElement findNextOutline(PsiElement element) {
PsiElement candidate = findRootLevel(element);
while(candidate != null && !isOutlineBlock(candidate)) {
candidate = candidate.getNextSibling();
}
return candidate;
}
private int outlineDepth(final PsiElement element) {
if(isOutlineBlock(element)) {
return element.getText().split("\\s")[0].length();
}
final PsiElement previousOutline = findPreviousOutline(element);
return previousOutline == null? 0 : outlineDepth(previousOutline);
}
private String createOutlineSameDepthAs(PsiElement currentOutline) {
return currentOutline.getText().split("\\s")[0] + " ";
}
private PsiElement findPreviousOutline(PsiElement element) {
PsiElement candidate = findRootLevel(element);
while (candidate != null && | !candidate.getNode().getElementType().equals(OrgTokenTypes.OUTLINE_BLOCK)) { |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/editor/actions/NewOutlineSameLevel.java | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
| import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl; | return element.getText().split("\\s")[0].length();
}
final PsiElement previousOutline = findPreviousOutline(element);
return previousOutline == null? 0 : outlineDepth(previousOutline);
}
private String createOutlineSameDepthAs(PsiElement currentOutline) {
return currentOutline.getText().split("\\s")[0] + " ";
}
private PsiElement findPreviousOutline(PsiElement element) {
PsiElement candidate = findRootLevel(element);
while (candidate != null &&
!candidate.getNode().getElementType().equals(OrgTokenTypes.OUTLINE_BLOCK)) {
candidate = candidate.getPrevSibling();
}
return candidate;
}
private PsiElement findRootLevel(PsiElement element) {
PsiElement candidate = element;
while(!(candidate.getParent() instanceof PsiFile)) {
candidate = candidate.getParent();
}
return candidate;
}
private PsiElement getParentOutlineOrSelf(@NotNull PsiElement element) { | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/editor/actions/NewOutlineSameLevel.java
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
return element.getText().split("\\s")[0].length();
}
final PsiElement previousOutline = findPreviousOutline(element);
return previousOutline == null? 0 : outlineDepth(previousOutline);
}
private String createOutlineSameDepthAs(PsiElement currentOutline) {
return currentOutline.getText().split("\\s")[0] + " ";
}
private PsiElement findPreviousOutline(PsiElement element) {
PsiElement candidate = findRootLevel(element);
while (candidate != null &&
!candidate.getNode().getElementType().equals(OrgTokenTypes.OUTLINE_BLOCK)) {
candidate = candidate.getPrevSibling();
}
return candidate;
}
private PsiElement findRootLevel(PsiElement element) {
PsiElement candidate = element;
while(!(candidate.getParent() instanceof PsiFile)) {
candidate = candidate.getParent();
}
return candidate;
}
private PsiElement getParentOutlineOrSelf(@NotNull PsiElement element) { | final OrgPsiElementImpl candidate = PsiTreeUtil.getTopmostParentOfType(element, OrgPsiElementImpl.class); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/parser/OrgParserDefinition.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
// public class OrgFileImpl extends PsiFileBase {
//
// public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
// super(fileViewProvider, OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return OrgFileType.INSTANCE;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
| import tk.skuro.idea.orgmode.OrgLanguage;
import tk.skuro.idea.orgmode.psi.OrgFileImpl;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.EmptyLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.tree.TokenSet; | package tk.skuro.idea.orgmode.parser;
/**
* Combines all the elements required to properly parse org-mode text
*
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgParserDefinition implements ParserDefinition {
/**
* Get the lexer for lexing files in the specified project.
*
* @param project the project to which the lexer is connected.
* @return an {@link EmptyLexer} instance.
*/
@NotNull
@Override
public Lexer createLexer(Project project) {
return new OrgLexer();
}
/**
* Get the parser for parsing files in the specified project.
*
* @param project the project to which the parser is connected.
* @return an {@link OrgParser} instance.
*/
@Override
public PsiParser createParser(Project project) {
return new OrgParser();
}
/**
* Get the element type of the node describing an org-mode file.
*
* @return A {@link IStubFileElementType} using {@link OrgLanguage#INSTANCE}
*/
@Override
public IFileElementType getFileNodeType() { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
// public class OrgFileImpl extends PsiFileBase {
//
// public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
// super(fileViewProvider, OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return OrgFileType.INSTANCE;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgParserDefinition.java
import tk.skuro.idea.orgmode.OrgLanguage;
import tk.skuro.idea.orgmode.psi.OrgFileImpl;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.EmptyLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.tree.TokenSet;
package tk.skuro.idea.orgmode.parser;
/**
* Combines all the elements required to properly parse org-mode text
*
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgParserDefinition implements ParserDefinition {
/**
* Get the lexer for lexing files in the specified project.
*
* @param project the project to which the lexer is connected.
* @return an {@link EmptyLexer} instance.
*/
@NotNull
@Override
public Lexer createLexer(Project project) {
return new OrgLexer();
}
/**
* Get the parser for parsing files in the specified project.
*
* @param project the project to which the parser is connected.
* @return an {@link OrgParser} instance.
*/
@Override
public PsiParser createParser(Project project) {
return new OrgParser();
}
/**
* Get the element type of the node describing an org-mode file.
*
* @return A {@link IStubFileElementType} using {@link OrgLanguage#INSTANCE}
*/
@Override
public IFileElementType getFileNodeType() { | return new IStubFileElementType(OrgLanguage.INSTANCE); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/parser/OrgParserDefinition.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
// public class OrgFileImpl extends PsiFileBase {
//
// public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
// super(fileViewProvider, OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return OrgFileType.INSTANCE;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
| import tk.skuro.idea.orgmode.OrgLanguage;
import tk.skuro.idea.orgmode.psi.OrgFileImpl;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.EmptyLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.tree.TokenSet; | * Get the set of token types which are treated as comments by the PSI builder.
*
* @return {@link TokenSet#EMPTY}
*/
@NotNull
@Override
public TokenSet getCommentTokens() {
return TokenSet.create(OrgTokenTypes.COMMENT);
}
/**
* Get the set of element types which are treated as string literals.
*
* @return {@link TokenSet#EMPTY}
*/
@NotNull
@Override
public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY;
}
/**
* Create a PSI element for the specified AST node.
*
* @param astNode the AST node.
* @return the PSI element matching the element type of the AST node.
*/
@NotNull
@Override
public PsiElement createElement(ASTNode astNode) { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
// public class OrgFileImpl extends PsiFileBase {
//
// public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
// super(fileViewProvider, OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return OrgFileType.INSTANCE;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgParserDefinition.java
import tk.skuro.idea.orgmode.OrgLanguage;
import tk.skuro.idea.orgmode.psi.OrgFileImpl;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.EmptyLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.tree.TokenSet;
* Get the set of token types which are treated as comments by the PSI builder.
*
* @return {@link TokenSet#EMPTY}
*/
@NotNull
@Override
public TokenSet getCommentTokens() {
return TokenSet.create(OrgTokenTypes.COMMENT);
}
/**
* Get the set of element types which are treated as string literals.
*
* @return {@link TokenSet#EMPTY}
*/
@NotNull
@Override
public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY;
}
/**
* Create a PSI element for the specified AST node.
*
* @param astNode the AST node.
* @return the PSI element matching the element type of the AST node.
*/
@NotNull
@Override
public PsiElement createElement(ASTNode astNode) { | return new OrgPsiElementImpl(astNode); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/parser/OrgParserDefinition.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
// public class OrgFileImpl extends PsiFileBase {
//
// public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
// super(fileViewProvider, OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return OrgFileType.INSTANCE;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
| import tk.skuro.idea.orgmode.OrgLanguage;
import tk.skuro.idea.orgmode.psi.OrgFileImpl;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.EmptyLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.tree.TokenSet; | * Get the set of element types which are treated as string literals.
*
* @return {@link TokenSet#EMPTY}
*/
@NotNull
@Override
public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY;
}
/**
* Create a PSI element for the specified AST node.
*
* @param astNode the AST node.
* @return the PSI element matching the element type of the AST node.
*/
@NotNull
@Override
public PsiElement createElement(ASTNode astNode) {
return new OrgPsiElementImpl(astNode);
}
/**
* Create a PSI element for the specified virtual file.
*
* @param fileViewProvider virtual file.
* @return the PSI file element.
*/
@Override
public PsiFile createFile(FileViewProvider fileViewProvider) { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
// public class OrgFileImpl extends PsiFileBase {
//
// public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
// super(fileViewProvider, OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return OrgFileType.INSTANCE;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgPsiElementImpl.java
// public class OrgPsiElementImpl extends ASTWrapperPsiElement {
// public OrgPsiElementImpl(@org.jetbrains.annotations.NotNull ASTNode astNode) {
// super(astNode);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgParserDefinition.java
import tk.skuro.idea.orgmode.OrgLanguage;
import tk.skuro.idea.orgmode.psi.OrgFileImpl;
import tk.skuro.idea.orgmode.psi.OrgPsiElementImpl;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.EmptyLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.tree.TokenSet;
* Get the set of element types which are treated as string literals.
*
* @return {@link TokenSet#EMPTY}
*/
@NotNull
@Override
public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY;
}
/**
* Create a PSI element for the specified AST node.
*
* @param astNode the AST node.
* @return the PSI element matching the element type of the AST node.
*/
@NotNull
@Override
public PsiElement createElement(ASTNode astNode) {
return new OrgPsiElementImpl(astNode);
}
/**
* Create a PSI element for the specified virtual file.
*
* @param fileViewProvider virtual file.
* @return the PSI file element.
*/
@Override
public PsiFile createFile(FileViewProvider fileViewProvider) { | return new OrgFileImpl(fileViewProvider); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenType.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
| import tk.skuro.idea.orgmode.OrgLanguage;
import org.jetbrains.annotations.NonNls;
import com.intellij.psi.tree.IElementType; | package tk.skuro.idea.orgmode.parser;
/**
* Class to represent an OrgElement token type for parsing org-mode text
*
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgTokenType extends IElementType {
public OrgTokenType(@NonNls String debugId) { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenType.java
import tk.skuro.idea.orgmode.OrgLanguage;
import org.jetbrains.annotations.NonNls;
import com.intellij.psi.tree.IElementType;
package tk.skuro.idea.orgmode.parser;
/**
* Class to represent an OrgElement token type for parsing org-mode text
*
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgTokenType extends IElementType {
public OrgTokenType(@NonNls String debugId) { | super(debugId, OrgLanguage.INSTANCE); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
| import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage;
import org.jetbrains.annotations.NotNull;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider; | package tk.skuro.idea.orgmode.psi;
/**
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgFileImpl extends PsiFileBase {
public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage;
import org.jetbrains.annotations.NotNull;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
package tk.skuro.idea.orgmode.psi;
/**
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgFileImpl extends PsiFileBase {
public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) { | super(fileViewProvider, OrgLanguage.INSTANCE); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
| import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage;
import org.jetbrains.annotations.NotNull;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider; | package tk.skuro.idea.orgmode.psi;
/**
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgFileImpl extends PsiFileBase {
public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
super(fileViewProvider, OrgLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/psi/OrgFileImpl.java
import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage;
import org.jetbrains.annotations.NotNull;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
package tk.skuro.idea.orgmode.psi;
/**
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgFileImpl extends PsiFileBase {
public OrgFileImpl(@NotNull FileViewProvider fileViewProvider) {
super(fileViewProvider, OrgLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() { | return OrgFileType.INSTANCE; |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/editor/OrgContextType.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
| import com.intellij.codeInsight.template.FileTypeBasedContextType;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage; | package tk.skuro.idea.orgmode.editor;
/**
* {@link com.intellij.codeInsight.template.FileTypeBasedContextType} for Orgmode.
*
* @author Adriean Khisbe <adriean.khisbe@live.fr>
* @since 0.2
*/
public class OrgContextType extends FileTypeBasedContextType {
protected OrgContextType() { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/editor/OrgContextType.java
import com.intellij.codeInsight.template.FileTypeBasedContextType;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage;
package tk.skuro.idea.orgmode.editor;
/**
* {@link com.intellij.codeInsight.template.FileTypeBasedContextType} for Orgmode.
*
* @author Adriean Khisbe <adriean.khisbe@live.fr>
* @since 0.2
*/
public class OrgContextType extends FileTypeBasedContextType {
protected OrgContextType() { | super("Org", "Org", OrgFileType.INSTANCE); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/editor/OrgContextType.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
| import com.intellij.codeInsight.template.FileTypeBasedContextType;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage; | package tk.skuro.idea.orgmode.editor;
/**
* {@link com.intellij.codeInsight.template.FileTypeBasedContextType} for Orgmode.
*
* @author Adriean Khisbe <adriean.khisbe@live.fr>
* @since 0.2
*/
public class OrgContextType extends FileTypeBasedContextType {
protected OrgContextType() {
super("Org", "Org", OrgFileType.INSTANCE);
}
@Override
public boolean isInContext(@NotNull PsiFile file, int offset) { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgFileType.java
// public class OrgFileType extends LanguageFileType {
//
// public final static OrgFileType INSTANCE = new OrgFileType();
//
// public final static String ORG_DEFAULT_EXTENSION = "org";
//
// protected OrgFileType() {
// super(OrgLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "OrgMode";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return OrgBundle.message("org.file.type.description");
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return OrgFileType.ORG_DEFAULT_EXTENSION;
// }
//
// @Override
// public Icon getIcon() {
// return OrgIcons.ORG_ICON;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/editor/OrgContextType.java
import com.intellij.codeInsight.template.FileTypeBasedContextType;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgFileType;
import tk.skuro.idea.orgmode.OrgLanguage;
package tk.skuro.idea.orgmode.editor;
/**
* {@link com.intellij.codeInsight.template.FileTypeBasedContextType} for Orgmode.
*
* @author Adriean Khisbe <adriean.khisbe@live.fr>
* @since 0.2
*/
public class OrgContextType extends FileTypeBasedContextType {
protected OrgContextType() {
super("Org", "Org", OrgFileType.INSTANCE);
}
@Override
public boolean isInContext(@NotNull PsiFile file, int offset) { | return file.getLanguage().isKindOf(OrgLanguage.INSTANCE); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/editor/folding/OrgFoldingBuilder.java | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import java.util.*; | package tk.skuro.idea.orgmode.editor.folding;
/**
* Enables blocks folding in org files, e.g. for code blocks, drawers, etc.
*
* @author Carlo Sciolla
* @since 0.3.0
*/
public class OrgFoldingBuilder implements FoldingBuilder {
private final static Set<IElementType> BLOCK_ELEMENTS = new HashSet<IElementType>(Arrays.asList( | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/editor/folding/OrgFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import java.util.*;
package tk.skuro.idea.orgmode.editor.folding;
/**
* Enables blocks folding in org files, e.g. for code blocks, drawers, etc.
*
* @author Carlo Sciolla
* @since 0.3.0
*/
public class OrgFoldingBuilder implements FoldingBuilder {
private final static Set<IElementType> BLOCK_ELEMENTS = new HashSet<IElementType>(Arrays.asList( | OrgTokenTypes.BLOCK, |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/parser/OrgElementType.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
| import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgLanguage; | package tk.skuro.idea.orgmode.parser;
/**
* Created by skuro on 08/08/16.
*/
public class OrgElementType extends IElementType {
public OrgElementType(@NotNull @NonNls String debugName) { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgLanguage.java
// public final class OrgLanguage extends Language {
//
// public static final String ORG_LANGUAGE_ID = "OrgMode";
// // see: http://lists.gnu.org/archive/html/emacs-diffs/2011-01/msg00290.html
// public static final String ORG_LANGUAGE_MIME_TYPE = "text/x-org";
//
// public static final OrgLanguage INSTANCE = new OrgLanguage();
//
// private OrgLanguage() {
// super(OrgLanguage.ORG_LANGUAGE_ID, OrgLanguage.ORG_LANGUAGE_MIME_TYPE);
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgElementType.java
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgLanguage;
package tk.skuro.idea.orgmode.parser;
/**
* Created by skuro on 08/08/16.
*/
public class OrgElementType extends IElementType {
public OrgElementType(@NotNull @NonNls String debugName) { | super(debugName, OrgLanguage.INSTANCE); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/highlight/OrgSyntaxHighlighter.java | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgLexer.java
// public class OrgLexer extends FlexAdapter {
//
// public OrgLexer() {
// super(new _OrgLexer((Reader)null));
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
| import com.intellij.psi.tree.TokenSet;
import tk.skuro.idea.orgmode.parser.OrgLexer;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import java.util.HashMap;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType; | package tk.skuro.idea.orgmode.highlight;
/**
* @author Carlo Sciolla
*/
public class OrgSyntaxHighlighter extends SyntaxHighlighterBase {
/**
* The map of text attribute keys for each token type.
*/
protected static final Map<IElementType, TextAttributesKey> ATTRIBUTES = new HashMap<IElementType, TextAttributesKey>();
static { | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgLexer.java
// public class OrgLexer extends FlexAdapter {
//
// public OrgLexer() {
// super(new _OrgLexer((Reader)null));
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgSyntaxHighlighter.java
import com.intellij.psi.tree.TokenSet;
import tk.skuro.idea.orgmode.parser.OrgLexer;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import java.util.HashMap;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
package tk.skuro.idea.orgmode.highlight;
/**
* @author Carlo Sciolla
*/
public class OrgSyntaxHighlighter extends SyntaxHighlighterBase {
/**
* The map of text attribute keys for each token type.
*/
protected static final Map<IElementType, TextAttributesKey> ATTRIBUTES = new HashMap<IElementType, TextAttributesKey>();
static { | fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.COMMENT), OrgHighlighterColors.COMMENTS_ATTR_KEY); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/highlight/OrgSyntaxHighlighter.java | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgLexer.java
// public class OrgLexer extends FlexAdapter {
//
// public OrgLexer() {
// super(new _OrgLexer((Reader)null));
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
| import com.intellij.psi.tree.TokenSet;
import tk.skuro.idea.orgmode.parser.OrgLexer;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import java.util.HashMap;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType; | package tk.skuro.idea.orgmode.highlight;
/**
* @author Carlo Sciolla
*/
public class OrgSyntaxHighlighter extends SyntaxHighlighterBase {
/**
* The map of text attribute keys for each token type.
*/
protected static final Map<IElementType, TextAttributesKey> ATTRIBUTES = new HashMap<IElementType, TextAttributesKey>();
static {
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.COMMENT), OrgHighlighterColors.COMMENTS_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.OUTLINE), OrgHighlighterColors.OUTLINE_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.BOLD), OrgHighlighterColors.BOLD_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.UNDERLINE), OrgHighlighterColors.UNDERLINE_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.KEYWORD), OrgHighlighterColors.KEYWORD_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.CODE), OrgHighlighterColors.CODE_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.BLOCK_CONTENT), OrgHighlighterColors.BLOCK_CONTENT_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.BLOCK_START, OrgTokenTypes.BLOCK_END),
OrgHighlighterColors.BLOCK_DELIM_ATTR_KEY);
// maybe refactor with static import
}
@NotNull
@Override
public Lexer getHighlightingLexer() { | // Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgLexer.java
// public class OrgLexer extends FlexAdapter {
//
// public OrgLexer() {
// super(new _OrgLexer((Reader)null));
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/parser/OrgTokenTypes.java
// public interface OrgTokenTypes {
//
// IElementType BLOCK = new OrgTokenType("BLOCK");
// IElementType DRAWER = new OrgTokenType("DRAWER");
// IElementType OUTLINE_BLOCK = new OrgTokenType("OUTLINE_BLOCK");
// IElementType TEXT_ELEMENT = new OrgTokenType("TEXT_ELEMENT");
//
// IElementType BLOCK_CONTENT = new OrgElementType("BLOCK_CONTENT");
// IElementType BLOCK_END = new OrgElementType("BLOCK_END");
// IElementType BLOCK_START = new OrgElementType("BLOCK_START");
// IElementType BOLD = new OrgElementType("BOLD");
// IElementType CODE = new OrgElementType("CODE");
// IElementType COMMENT = new OrgElementType("COMMENT");
// IElementType CRLF = new OrgElementType("CRLF");
// IElementType DRAWER_CONTENT = new OrgElementType("DRAWER_CONTENT");
// IElementType DRAWER_DELIMITER = new OrgElementType("DRAWER_DELIMITER");
// IElementType KEYWORD = new OrgElementType("KEYWORD");
// IElementType OUTLINE = new OrgElementType("OUTLINE");
// IElementType PROPERTIES = new OrgElementType("PROPERTIES");
// IElementType TEXT = new OrgElementType("TEXT");
// IElementType UNDERLINE = new OrgElementType("UNDERLINE");
// IElementType UNMATCHED_DELIMITER = new OrgElementType("UNMATCHED_DELIMITER");
// IElementType WHITE_SPACE = new OrgElementType("WHITE_SPACE");
//
// class Factory {
// public static PsiElement createElement(ASTNode node) {
// IElementType type = node.getElementType();
// if (type == BLOCK) {
// return new OrgBlockImpl(node);
// }
// else if (type == DRAWER) {
// return new OrgDrawerImpl(node);
// }
// else if (type == OUTLINE_BLOCK) {
// return new OrgOutlineBlockImpl(node);
// }
// else if (type == TEXT_ELEMENT) {
// return new OrgTextElementImpl(node);
// }
// throw new AssertionError("Unknown element type: " + type);
// }
// }
// }
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgSyntaxHighlighter.java
import com.intellij.psi.tree.TokenSet;
import tk.skuro.idea.orgmode.parser.OrgLexer;
import tk.skuro.idea.orgmode.parser.OrgTokenTypes;
import java.util.HashMap;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
package tk.skuro.idea.orgmode.highlight;
/**
* @author Carlo Sciolla
*/
public class OrgSyntaxHighlighter extends SyntaxHighlighterBase {
/**
* The map of text attribute keys for each token type.
*/
protected static final Map<IElementType, TextAttributesKey> ATTRIBUTES = new HashMap<IElementType, TextAttributesKey>();
static {
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.COMMENT), OrgHighlighterColors.COMMENTS_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.OUTLINE), OrgHighlighterColors.OUTLINE_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.BOLD), OrgHighlighterColors.BOLD_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.UNDERLINE), OrgHighlighterColors.UNDERLINE_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.KEYWORD), OrgHighlighterColors.KEYWORD_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.CODE), OrgHighlighterColors.CODE_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.BLOCK_CONTENT), OrgHighlighterColors.BLOCK_CONTENT_ATTR_KEY);
fillMap(ATTRIBUTES, TokenSet.create(OrgTokenTypes.BLOCK_START, OrgTokenTypes.BLOCK_END),
OrgHighlighterColors.BLOCK_DELIM_ATTR_KEY);
// maybe refactor with static import
}
@NotNull
@Override
public Lexer getHighlightingLexer() { | return new OrgLexer(); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/highlight/OrgColorSettingsPage.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgBundle.java
// public class OrgBundle {
// @NonNls
// protected static final String PATH_TO_BUNDLE = "messages.OrgBundle";
// private static Reference<ResourceBundle> reference;
//
// private OrgBundle() {
// }
//
// /**
// * Retrieve Message from bundle
// * @param key message key
// * @param params optinal value for placeholders
// * @return Message associated to key
// */
// public static String message(@PropertyKey(resourceBundle = PATH_TO_BUNDLE)String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (reference != null) bundle = reference.get();
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(PATH_TO_BUNDLE);
// reference = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgIcons.java
// public interface OrgIcons {
// Icon ORG_ICON = IconLoader.getIcon("/org/fileType.png");
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgHighlighterColors.java
// public interface OrgHighlighterColors {
//
// /**
// * Default style for outline
// */
// TextAttributesKey OUTLINE_ATTR_KEY = createTextAttributesKey("ORG.OUTLINE", KEYWORD);
//
// /**
// * Default style of comments
// */
// TextAttributesKey COMMENTS_ATTR_KEY = createTextAttributesKey("ORG.COMMENT", LINE_COMMENT);
//
// /**
// * Default style of comment keyword {@code #+TITLE}
// */
// TextAttributesKey KEYWORD_ATTR_KEY = createTextAttributesKey("ORG.KEYWORD", LINE_COMMENT);
//
// /**
// * Default style of block delimiter
// */
// TextAttributesKey BLOCK_DELIM_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_DELIMITER", KEYWORD_ATTR_KEY);
//
// /**
// * Default style of code
// */
// TextAttributesKey CODE_ATTR_KEY = createTextAttributesKey("ORG.CODE", TEMPLATE_LANGUAGE_COLOR);
//
// /**
// * Default style of block content
// */
// TextAttributesKey BLOCK_CONTENT_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_CONTENT", CODE_ATTR_KEY);
//
// /**
// * Default style of Bold text
// */
// TextAttributesKey BOLD_ATTR_KEY = createTextAttributesKey("ORG.BOLD", STRING);
// /**
// * Default style of underline text
// */
// TextAttributesKey UNDERLINE_ATTR_KEY = createTextAttributesKey("ORG.UNDERLINE", STRING);
//
//
// }
| import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgBundle;
import tk.skuro.idea.orgmode.OrgIcons;
import javax.swing.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static tk.skuro.idea.orgmode.highlight.OrgHighlighterColors.*; | package tk.skuro.idea.orgmode.highlight;
/**
* Configuration for the color font page of Org language
*
* @author Carlo Sciolla
*/
public class OrgColorSettingsPage implements ColorSettingsPage {
/**
* The {@link Logger}.
*/
private final static Logger LOGGER = Logger.getInstance(OrgColorSettingsPage.class);
private static final String SAMPLE_ORG_DOCUMENT_PATH = "/sample.org";
private static final String SAMPLE_ORG_DOCUMENT = loadSampleOrgDocument();
/**
* The set of {@link AttributesDescriptor} defining the configurable options in the dialog.
*/
protected final List<AttributesDescriptor> attributeDescriptors = new LinkedList<AttributesDescriptor>();
public OrgColorSettingsPage() {
// Populate attribute descriptors.
addAttribute("org.editor.colorsettingspage.keyword", KEYWORD_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.comment", COMMENTS_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.outline", OUTLINE_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.underline", UNDERLINE_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.bold", BOLD_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.code", CODE_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.block.delimiter", BLOCK_DELIM_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.block.content", BLOCK_CONTENT_ATTR_KEY);
}
/**
* Load the sample text to be displayed in the preview pane.
*
* @return the text loaded from {@link #SAMPLE_ORG_DOCUMENT_PATH}
* @see #getDemoText()
* @see #SAMPLE_ORG_DOCUMENT_PATH
* @see #SAMPLE_ORG_DOCUMENT
*/
protected static String loadSampleOrgDocument() {
// ¤note: File must have unix style separators: \n
try {
return FileUtil.loadTextAndClose(new InputStreamReader(
OrgColorSettingsPage.class.getResourceAsStream(SAMPLE_ORG_DOCUMENT_PATH)));
} catch (Exception e) {
LOGGER.error("Failed loading sample Org document", e);
} | // Path: src/main/java/tk/skuro/idea/orgmode/OrgBundle.java
// public class OrgBundle {
// @NonNls
// protected static final String PATH_TO_BUNDLE = "messages.OrgBundle";
// private static Reference<ResourceBundle> reference;
//
// private OrgBundle() {
// }
//
// /**
// * Retrieve Message from bundle
// * @param key message key
// * @param params optinal value for placeholders
// * @return Message associated to key
// */
// public static String message(@PropertyKey(resourceBundle = PATH_TO_BUNDLE)String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (reference != null) bundle = reference.get();
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(PATH_TO_BUNDLE);
// reference = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgIcons.java
// public interface OrgIcons {
// Icon ORG_ICON = IconLoader.getIcon("/org/fileType.png");
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgHighlighterColors.java
// public interface OrgHighlighterColors {
//
// /**
// * Default style for outline
// */
// TextAttributesKey OUTLINE_ATTR_KEY = createTextAttributesKey("ORG.OUTLINE", KEYWORD);
//
// /**
// * Default style of comments
// */
// TextAttributesKey COMMENTS_ATTR_KEY = createTextAttributesKey("ORG.COMMENT", LINE_COMMENT);
//
// /**
// * Default style of comment keyword {@code #+TITLE}
// */
// TextAttributesKey KEYWORD_ATTR_KEY = createTextAttributesKey("ORG.KEYWORD", LINE_COMMENT);
//
// /**
// * Default style of block delimiter
// */
// TextAttributesKey BLOCK_DELIM_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_DELIMITER", KEYWORD_ATTR_KEY);
//
// /**
// * Default style of code
// */
// TextAttributesKey CODE_ATTR_KEY = createTextAttributesKey("ORG.CODE", TEMPLATE_LANGUAGE_COLOR);
//
// /**
// * Default style of block content
// */
// TextAttributesKey BLOCK_CONTENT_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_CONTENT", CODE_ATTR_KEY);
//
// /**
// * Default style of Bold text
// */
// TextAttributesKey BOLD_ATTR_KEY = createTextAttributesKey("ORG.BOLD", STRING);
// /**
// * Default style of underline text
// */
// TextAttributesKey UNDERLINE_ATTR_KEY = createTextAttributesKey("ORG.UNDERLINE", STRING);
//
//
// }
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgColorSettingsPage.java
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgBundle;
import tk.skuro.idea.orgmode.OrgIcons;
import javax.swing.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static tk.skuro.idea.orgmode.highlight.OrgHighlighterColors.*;
package tk.skuro.idea.orgmode.highlight;
/**
* Configuration for the color font page of Org language
*
* @author Carlo Sciolla
*/
public class OrgColorSettingsPage implements ColorSettingsPage {
/**
* The {@link Logger}.
*/
private final static Logger LOGGER = Logger.getInstance(OrgColorSettingsPage.class);
private static final String SAMPLE_ORG_DOCUMENT_PATH = "/sample.org";
private static final String SAMPLE_ORG_DOCUMENT = loadSampleOrgDocument();
/**
* The set of {@link AttributesDescriptor} defining the configurable options in the dialog.
*/
protected final List<AttributesDescriptor> attributeDescriptors = new LinkedList<AttributesDescriptor>();
public OrgColorSettingsPage() {
// Populate attribute descriptors.
addAttribute("org.editor.colorsettingspage.keyword", KEYWORD_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.comment", COMMENTS_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.outline", OUTLINE_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.underline", UNDERLINE_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.bold", BOLD_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.code", CODE_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.block.delimiter", BLOCK_DELIM_ATTR_KEY);
addAttribute("org.editor.colorsettingspage.block.content", BLOCK_CONTENT_ATTR_KEY);
}
/**
* Load the sample text to be displayed in the preview pane.
*
* @return the text loaded from {@link #SAMPLE_ORG_DOCUMENT_PATH}
* @see #getDemoText()
* @see #SAMPLE_ORG_DOCUMENT_PATH
* @see #SAMPLE_ORG_DOCUMENT
*/
protected static String loadSampleOrgDocument() {
// ¤note: File must have unix style separators: \n
try {
return FileUtil.loadTextAndClose(new InputStreamReader(
OrgColorSettingsPage.class.getResourceAsStream(SAMPLE_ORG_DOCUMENT_PATH)));
} catch (Exception e) {
LOGGER.error("Failed loading sample Org document", e);
} | return OrgBundle.message("org.editor.colorsettingspage.sample-loading-error"); |
skuro/org4idea | src/main/java/tk/skuro/idea/orgmode/highlight/OrgColorSettingsPage.java | // Path: src/main/java/tk/skuro/idea/orgmode/OrgBundle.java
// public class OrgBundle {
// @NonNls
// protected static final String PATH_TO_BUNDLE = "messages.OrgBundle";
// private static Reference<ResourceBundle> reference;
//
// private OrgBundle() {
// }
//
// /**
// * Retrieve Message from bundle
// * @param key message key
// * @param params optinal value for placeholders
// * @return Message associated to key
// */
// public static String message(@PropertyKey(resourceBundle = PATH_TO_BUNDLE)String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (reference != null) bundle = reference.get();
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(PATH_TO_BUNDLE);
// reference = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgIcons.java
// public interface OrgIcons {
// Icon ORG_ICON = IconLoader.getIcon("/org/fileType.png");
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgHighlighterColors.java
// public interface OrgHighlighterColors {
//
// /**
// * Default style for outline
// */
// TextAttributesKey OUTLINE_ATTR_KEY = createTextAttributesKey("ORG.OUTLINE", KEYWORD);
//
// /**
// * Default style of comments
// */
// TextAttributesKey COMMENTS_ATTR_KEY = createTextAttributesKey("ORG.COMMENT", LINE_COMMENT);
//
// /**
// * Default style of comment keyword {@code #+TITLE}
// */
// TextAttributesKey KEYWORD_ATTR_KEY = createTextAttributesKey("ORG.KEYWORD", LINE_COMMENT);
//
// /**
// * Default style of block delimiter
// */
// TextAttributesKey BLOCK_DELIM_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_DELIMITER", KEYWORD_ATTR_KEY);
//
// /**
// * Default style of code
// */
// TextAttributesKey CODE_ATTR_KEY = createTextAttributesKey("ORG.CODE", TEMPLATE_LANGUAGE_COLOR);
//
// /**
// * Default style of block content
// */
// TextAttributesKey BLOCK_CONTENT_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_CONTENT", CODE_ATTR_KEY);
//
// /**
// * Default style of Bold text
// */
// TextAttributesKey BOLD_ATTR_KEY = createTextAttributesKey("ORG.BOLD", STRING);
// /**
// * Default style of underline text
// */
// TextAttributesKey UNDERLINE_ATTR_KEY = createTextAttributesKey("ORG.UNDERLINE", STRING);
//
//
// }
| import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgBundle;
import tk.skuro.idea.orgmode.OrgIcons;
import javax.swing.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static tk.skuro.idea.orgmode.highlight.OrgHighlighterColors.*; | * @return the text loaded from {@link #SAMPLE_ORG_DOCUMENT_PATH}
* @see #getDemoText()
* @see #SAMPLE_ORG_DOCUMENT_PATH
* @see #SAMPLE_ORG_DOCUMENT
*/
protected static String loadSampleOrgDocument() {
// ¤note: File must have unix style separators: \n
try {
return FileUtil.loadTextAndClose(new InputStreamReader(
OrgColorSettingsPage.class.getResourceAsStream(SAMPLE_ORG_DOCUMENT_PATH)));
} catch (Exception e) {
LOGGER.error("Failed loading sample Org document", e);
}
return OrgBundle.message("org.editor.colorsettingspage.sample-loading-error");
}
/**
* Util factorising method to add attribute in a more succint dry way
*
* @param name the key of the message bundle for the name of attribut
* @param textAttributesKey the attribute key to bind
* @return whether the attribute was adde or not
*/
private boolean addAttribute(String name, TextAttributesKey textAttributesKey) {
return attributeDescriptors.add(
new AttributesDescriptor(OrgBundle.message(name), textAttributesKey));
}
@Override
public Icon getIcon() { | // Path: src/main/java/tk/skuro/idea/orgmode/OrgBundle.java
// public class OrgBundle {
// @NonNls
// protected static final String PATH_TO_BUNDLE = "messages.OrgBundle";
// private static Reference<ResourceBundle> reference;
//
// private OrgBundle() {
// }
//
// /**
// * Retrieve Message from bundle
// * @param key message key
// * @param params optinal value for placeholders
// * @return Message associated to key
// */
// public static String message(@PropertyKey(resourceBundle = PATH_TO_BUNDLE)String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (reference != null) bundle = reference.get();
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(PATH_TO_BUNDLE);
// reference = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/OrgIcons.java
// public interface OrgIcons {
// Icon ORG_ICON = IconLoader.getIcon("/org/fileType.png");
// }
//
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgHighlighterColors.java
// public interface OrgHighlighterColors {
//
// /**
// * Default style for outline
// */
// TextAttributesKey OUTLINE_ATTR_KEY = createTextAttributesKey("ORG.OUTLINE", KEYWORD);
//
// /**
// * Default style of comments
// */
// TextAttributesKey COMMENTS_ATTR_KEY = createTextAttributesKey("ORG.COMMENT", LINE_COMMENT);
//
// /**
// * Default style of comment keyword {@code #+TITLE}
// */
// TextAttributesKey KEYWORD_ATTR_KEY = createTextAttributesKey("ORG.KEYWORD", LINE_COMMENT);
//
// /**
// * Default style of block delimiter
// */
// TextAttributesKey BLOCK_DELIM_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_DELIMITER", KEYWORD_ATTR_KEY);
//
// /**
// * Default style of code
// */
// TextAttributesKey CODE_ATTR_KEY = createTextAttributesKey("ORG.CODE", TEMPLATE_LANGUAGE_COLOR);
//
// /**
// * Default style of block content
// */
// TextAttributesKey BLOCK_CONTENT_ATTR_KEY = createTextAttributesKey("ORG.BLOCK_CONTENT", CODE_ATTR_KEY);
//
// /**
// * Default style of Bold text
// */
// TextAttributesKey BOLD_ATTR_KEY = createTextAttributesKey("ORG.BOLD", STRING);
// /**
// * Default style of underline text
// */
// TextAttributesKey UNDERLINE_ATTR_KEY = createTextAttributesKey("ORG.UNDERLINE", STRING);
//
//
// }
// Path: src/main/java/tk/skuro/idea/orgmode/highlight/OrgColorSettingsPage.java
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import tk.skuro.idea.orgmode.OrgBundle;
import tk.skuro.idea.orgmode.OrgIcons;
import javax.swing.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static tk.skuro.idea.orgmode.highlight.OrgHighlighterColors.*;
* @return the text loaded from {@link #SAMPLE_ORG_DOCUMENT_PATH}
* @see #getDemoText()
* @see #SAMPLE_ORG_DOCUMENT_PATH
* @see #SAMPLE_ORG_DOCUMENT
*/
protected static String loadSampleOrgDocument() {
// ¤note: File must have unix style separators: \n
try {
return FileUtil.loadTextAndClose(new InputStreamReader(
OrgColorSettingsPage.class.getResourceAsStream(SAMPLE_ORG_DOCUMENT_PATH)));
} catch (Exception e) {
LOGGER.error("Failed loading sample Org document", e);
}
return OrgBundle.message("org.editor.colorsettingspage.sample-loading-error");
}
/**
* Util factorising method to add attribute in a more succint dry way
*
* @param name the key of the message bundle for the name of attribut
* @param textAttributesKey the attribute key to bind
* @return whether the attribute was adde or not
*/
private boolean addAttribute(String name, TextAttributesKey textAttributesKey) {
return attributeDescriptors.add(
new AttributesDescriptor(OrgBundle.message(name), textAttributesKey));
}
@Override
public Icon getIcon() { | return OrgIcons.ORG_ICON; |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/MonitoringPipelineMavenPluginDaoDecorator.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; | package org.jenkinsci.plugins.pipeline.maven.dao;
public class MonitoringPipelineMavenPluginDaoDecorator extends AbstractPipelineMavenPluginDaoDecorator {
private final AtomicLong findDurationInNanos = new AtomicLong();
private final AtomicInteger findCount = new AtomicInteger();
private final AtomicLong writeDurationInNanos = new AtomicLong();
private final AtomicInteger writeCount = new AtomicInteger();
public MonitoringPipelineMavenPluginDaoDecorator(@Nonnull PipelineMavenPluginDao delegate) {
super(delegate);
}
@Override
public void recordDependency(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String scope, boolean ignoreUpstreamTriggers, String classifier) {
executeMonitored(() -> super.recordDependency(jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers, classifier));
}
@Override
public void recordParentProject(@Nonnull String jobFullName, int buildNumber, @Nonnull String parentGroupId, @Nonnull String parentArtifactId, @Nonnull String parentVersion, boolean ignoreUpstreamTriggers) {
executeMonitored(() -> super.recordParentProject(jobFullName, buildNumber, parentGroupId, parentArtifactId, parentVersion, ignoreUpstreamTriggers));
}
@Override
public void recordGeneratedArtifact(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String baseVersion, @Nullable String repositoryUrl, boolean skipDownstreamTriggers, String extension, String classifier) {
executeMonitored(() -> super.recordGeneratedArtifact(jobFullName, buildNumber, groupId, artifactId, version, type, baseVersion, repositoryUrl, skipDownstreamTriggers, extension, classifier));
}
@Override
public void recordBuildUpstreamCause(String upstreamJobName, int upstreamBuildNumber, String downstreamJobName, int downstreamBuildNumber) {
executeMonitored(() -> super.recordBuildUpstreamCause(upstreamJobName, upstreamBuildNumber, downstreamJobName, downstreamBuildNumber));
}
@Override
@Nonnull | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/MonitoringPipelineMavenPluginDaoDecorator.java
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
package org.jenkinsci.plugins.pipeline.maven.dao;
public class MonitoringPipelineMavenPluginDaoDecorator extends AbstractPipelineMavenPluginDaoDecorator {
private final AtomicLong findDurationInNanos = new AtomicLong();
private final AtomicInteger findCount = new AtomicInteger();
private final AtomicLong writeDurationInNanos = new AtomicLong();
private final AtomicInteger writeCount = new AtomicInteger();
public MonitoringPipelineMavenPluginDaoDecorator(@Nonnull PipelineMavenPluginDao delegate) {
super(delegate);
}
@Override
public void recordDependency(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String scope, boolean ignoreUpstreamTriggers, String classifier) {
executeMonitored(() -> super.recordDependency(jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers, classifier));
}
@Override
public void recordParentProject(@Nonnull String jobFullName, int buildNumber, @Nonnull String parentGroupId, @Nonnull String parentArtifactId, @Nonnull String parentVersion, boolean ignoreUpstreamTriggers) {
executeMonitored(() -> super.recordParentProject(jobFullName, buildNumber, parentGroupId, parentArtifactId, parentVersion, ignoreUpstreamTriggers));
}
@Override
public void recordGeneratedArtifact(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String baseVersion, @Nullable String repositoryUrl, boolean skipDownstreamTriggers, String extension, String classifier) {
executeMonitored(() -> super.recordGeneratedArtifact(jobFullName, buildNumber, groupId, artifactId, version, type, baseVersion, repositoryUrl, skipDownstreamTriggers, extension, classifier));
}
@Override
public void recordBuildUpstreamCause(String upstreamJobName, int upstreamBuildNumber, String downstreamJobName, int downstreamBuildNumber) {
executeMonitored(() -> super.recordBuildUpstreamCause(upstreamJobName, upstreamBuildNumber, downstreamJobName, downstreamBuildNumber));
}
@Override
@Nonnull | public List<MavenDependency> listDependencies(@Nonnull String jobFullName, int buildNumber) { |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/WithMavenStepMavenExecResolutionTest.java | // Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/MavenWithMavenHomeJavaContainer.java
// @DockerFixture(id = "maven-with-maven-home-java", ports = {22, 8080})
// public class MavenWithMavenHomeJavaContainer extends JavaContainer {
// }
//
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/NonMavenJavaContainer.java
// @DockerFixture(id = "non-maven-java", ports = {22, 8080})
// public class NonMavenJavaContainer extends JavaContainer {
// }
| import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.model.DownloadService;
import hudson.model.Result;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.slaves.DumbSlave;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.Maven;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tools.InstallSourceProperty;
import org.jenkinsci.plugins.pipeline.maven.docker.JavaGitContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.MavenWithMavenHomeJavaContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.NonMavenJavaContainer;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.test.acceptance.docker.DockerRule;
import org.jenkinsci.test.acceptance.docker.fixtures.SshdContainer;
import org.jenkinsci.utils.process.CommandBuilder;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat; | /*
* The MIT License
*
* Copyright 2016 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven;
@Issue("JENKINS-43651")
public class WithMavenStepMavenExecResolutionTest extends AbstractIntegrationTest {
private static final String SSH_CREDENTIALS_ID = "test";
private static final String AGENT_NAME = "remote";
private static final String MAVEN_GLOBAL_TOOL_NAME = "maven";
private static final String SLAVE_BASE_PATH = "/home/test/slave";
@Rule | // Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/MavenWithMavenHomeJavaContainer.java
// @DockerFixture(id = "maven-with-maven-home-java", ports = {22, 8080})
// public class MavenWithMavenHomeJavaContainer extends JavaContainer {
// }
//
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/NonMavenJavaContainer.java
// @DockerFixture(id = "non-maven-java", ports = {22, 8080})
// public class NonMavenJavaContainer extends JavaContainer {
// }
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/WithMavenStepMavenExecResolutionTest.java
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.model.DownloadService;
import hudson.model.Result;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.slaves.DumbSlave;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.Maven;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tools.InstallSourceProperty;
import org.jenkinsci.plugins.pipeline.maven.docker.JavaGitContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.MavenWithMavenHomeJavaContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.NonMavenJavaContainer;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.test.acceptance.docker.DockerRule;
import org.jenkinsci.test.acceptance.docker.fixtures.SshdContainer;
import org.jenkinsci.utils.process.CommandBuilder;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* The MIT License
*
* Copyright 2016 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven;
@Issue("JENKINS-43651")
public class WithMavenStepMavenExecResolutionTest extends AbstractIntegrationTest {
private static final String SSH_CREDENTIALS_ID = "test";
private static final String AGENT_NAME = "remote";
private static final String MAVEN_GLOBAL_TOOL_NAME = "maven";
private static final String SLAVE_BASE_PATH = "/home/test/slave";
@Rule | public DockerRule<NonMavenJavaContainer> nonMavenContainerRule = new DockerRule<>(NonMavenJavaContainer.class); |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/WithMavenStepMavenExecResolutionTest.java | // Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/MavenWithMavenHomeJavaContainer.java
// @DockerFixture(id = "maven-with-maven-home-java", ports = {22, 8080})
// public class MavenWithMavenHomeJavaContainer extends JavaContainer {
// }
//
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/NonMavenJavaContainer.java
// @DockerFixture(id = "non-maven-java", ports = {22, 8080})
// public class NonMavenJavaContainer extends JavaContainer {
// }
| import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.model.DownloadService;
import hudson.model.Result;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.slaves.DumbSlave;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.Maven;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tools.InstallSourceProperty;
import org.jenkinsci.plugins.pipeline.maven.docker.JavaGitContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.MavenWithMavenHomeJavaContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.NonMavenJavaContainer;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.test.acceptance.docker.DockerRule;
import org.jenkinsci.test.acceptance.docker.fixtures.SshdContainer;
import org.jenkinsci.utils.process.CommandBuilder;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat; | /*
* The MIT License
*
* Copyright 2016 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven;
@Issue("JENKINS-43651")
public class WithMavenStepMavenExecResolutionTest extends AbstractIntegrationTest {
private static final String SSH_CREDENTIALS_ID = "test";
private static final String AGENT_NAME = "remote";
private static final String MAVEN_GLOBAL_TOOL_NAME = "maven";
private static final String SLAVE_BASE_PATH = "/home/test/slave";
@Rule
public DockerRule<NonMavenJavaContainer> nonMavenContainerRule = new DockerRule<>(NonMavenJavaContainer.class);
@Rule
public DockerRule<JavaGitContainer> mavenWithoutMavenHomeContainerRule = new DockerRule<>(JavaGitContainer.class);
@Rule | // Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/MavenWithMavenHomeJavaContainer.java
// @DockerFixture(id = "maven-with-maven-home-java", ports = {22, 8080})
// public class MavenWithMavenHomeJavaContainer extends JavaContainer {
// }
//
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/docker/NonMavenJavaContainer.java
// @DockerFixture(id = "non-maven-java", ports = {22, 8080})
// public class NonMavenJavaContainer extends JavaContainer {
// }
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/WithMavenStepMavenExecResolutionTest.java
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.model.DownloadService;
import hudson.model.Result;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.slaves.DumbSlave;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.Maven;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tools.InstallSourceProperty;
import org.jenkinsci.plugins.pipeline.maven.docker.JavaGitContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.MavenWithMavenHomeJavaContainer;
import org.jenkinsci.plugins.pipeline.maven.docker.NonMavenJavaContainer;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.test.acceptance.docker.DockerRule;
import org.jenkinsci.test.acceptance.docker.fixtures.SshdContainer;
import org.jenkinsci.utils.process.CommandBuilder;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* The MIT License
*
* Copyright 2016 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven;
@Issue("JENKINS-43651")
public class WithMavenStepMavenExecResolutionTest extends AbstractIntegrationTest {
private static final String SSH_CREDENTIALS_ID = "test";
private static final String AGENT_NAME = "remote";
private static final String MAVEN_GLOBAL_TOOL_NAME = "maven";
private static final String SLAVE_BASE_PATH = "/home/test/slave";
@Rule
public DockerRule<NonMavenJavaContainer> nonMavenContainerRule = new DockerRule<>(NonMavenJavaContainer.class);
@Rule
public DockerRule<JavaGitContainer> mavenWithoutMavenHomeContainerRule = new DockerRule<>(JavaGitContainer.class);
@Rule | public DockerRule<MavenWithMavenHomeJavaContainer> mavenWithMavenHomeContainerRule = new DockerRule<>(MavenWithMavenHomeJavaContainer.class); |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/DependenciesFingerprintPublisher.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import hudson.Extension;
import hudson.FilePath;
import hudson.model.FingerprintMap;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.Fingerprinter;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.MavenPublisher;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.w3c.dom.Element;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.jenkinsci.plugins.pipeline.maven.publishers.DependenciesLister.listDependencies; |
private boolean includeScopeTest;
private boolean includeScopeProvided = true;
@DataBoundConstructor
public DependenciesFingerprintPublisher() {
super();
}
protected Set<String> getIncludedScopes() {
Set<String> includedScopes = new TreeSet<>();
if (includeScopeCompile)
includedScopes.add("compile");
if (includeScopeRuntime)
includedScopes.add("runtime");
if (includeScopeProvided)
includedScopes.add("provided");
if (includeScopeTest)
includedScopes.add("test");
return includedScopes;
}
@Override
public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException {
Run run = context.get(Run.class);
TaskListener listener = context.get(TaskListener.class);
FilePath workspace = context.get(FilePath.class);
| // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/DependenciesFingerprintPublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.model.FingerprintMap;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.Fingerprinter;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.MavenPublisher;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.w3c.dom.Element;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.jenkinsci.plugins.pipeline.maven.publishers.DependenciesLister.listDependencies;
private boolean includeScopeTest;
private boolean includeScopeProvided = true;
@DataBoundConstructor
public DependenciesFingerprintPublisher() {
super();
}
protected Set<String> getIncludedScopes() {
Set<String> includedScopes = new TreeSet<>();
if (includeScopeCompile)
includedScopes.add("compile");
if (includeScopeRuntime)
includedScopes.add("runtime");
if (includeScopeProvided)
includedScopes.add("provided");
if (includeScopeTest)
includedScopes.add("test");
return includedScopes;
}
@Override
public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException {
Run run = context.get(Run.class);
TaskListener listener = context.get(TaskListener.class);
FilePath workspace = context.get(FilePath.class);
| List<MavenDependency> dependencies = listDependencies(mavenSpyLogsElt, LOGGER); |
jenkinsci/pipeline-maven-plugin | maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/InvokerStartExecutionHandler.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpy.java
// public final static String DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME = "JENKINS_MAVEN_AGENT_DISABLED";
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
| import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import static org.jenkinsci.plugins.pipeline.maven.eventspy.JenkinsMavenEventSpy.DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.execution.ExecutionEvent; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* Handler to alter the
* <code>org.apache.maven.plugins:maven-invoker-plugin:run</code> goal : it will
* append the <code>JENKINS_MAVEN_AGENT_DISABLED</code> (set to
* <code>true</code>) to the environment.
* <p>
* Thus our spy will not run during Invoker integration tests, to avoid
* recording integration tests artifacts and dependencies.
*
* @author <a href="mailto:benoit.guerin1@free.fr">Benoit Guérin</a>
*
*/
public class InvokerStartExecutionHandler extends AbstractExecutionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
| // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpy.java
// public final static String DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME = "JENKINS_MAVEN_AGENT_DISABLED";
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/InvokerStartExecutionHandler.java
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import static org.jenkinsci.plugins.pipeline.maven.eventspy.JenkinsMavenEventSpy.DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.execution.ExecutionEvent;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* Handler to alter the
* <code>org.apache.maven.plugins:maven-invoker-plugin:run</code> goal : it will
* append the <code>JENKINS_MAVEN_AGENT_DISABLED</code> (set to
* <code>true</code>) to the environment.
* <p>
* Thus our spy will not run during Invoker integration tests, to avoid
* recording integration tests artifacts and dependencies.
*
* @author <a href="mailto:benoit.guerin1@free.fr">Benoit Guérin</a>
*
*/
public class InvokerStartExecutionHandler extends AbstractExecutionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
| public InvokerStartExecutionHandler(final MavenEventReporter reporter) { |
jenkinsci/pipeline-maven-plugin | maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/InvokerStartExecutionHandler.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpy.java
// public final static String DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME = "JENKINS_MAVEN_AGENT_DISABLED";
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
| import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import static org.jenkinsci.plugins.pipeline.maven.eventspy.JenkinsMavenEventSpy.DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.execution.ExecutionEvent; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* Handler to alter the
* <code>org.apache.maven.plugins:maven-invoker-plugin:run</code> goal : it will
* append the <code>JENKINS_MAVEN_AGENT_DISABLED</code> (set to
* <code>true</code>) to the environment.
* <p>
* Thus our spy will not run during Invoker integration tests, to avoid
* recording integration tests artifacts and dependencies.
*
* @author <a href="mailto:benoit.guerin1@free.fr">Benoit Guérin</a>
*
*/
public class InvokerStartExecutionHandler extends AbstractExecutionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
public InvokerStartExecutionHandler(final MavenEventReporter reporter) {
super(reporter);
}
@Override
@Nullable
protected ExecutionEvent.Type getSupportedType() {
return ExecutionEvent.Type.MojoStarted;
}
@Nullable
@Override
protected String getSupportedPluginGoal() {
return "org.apache.maven.plugins:maven-invoker-plugin:run";
}
@NonNull
@Override
protected List<String> getConfigurationParametersToReport(final ExecutionEvent executionEvent) {
return new ArrayList<String>();
}
@Override
public boolean _handle(final ExecutionEvent executionEvent) {
final boolean result = super._handle(executionEvent);
logger.debug("[jenkins-event-spy] Start of goal " + getSupportedPluginGoal() + ", disabling spy in IT tests.");
// First retrieve the "environmentVariables" configuration of the captured Mojo
Xpp3Dom env = executionEvent.getMojoExecution().getConfiguration().getChild("environmentVariables");
if (env == null) {
// if the mojo does not have such a configuration, create an empty one
env = new Xpp3Dom("environmentVariables");
executionEvent.getMojoExecution().getConfiguration().addChild(env);
}
// Finally, adding our environment variable to disable our spy during the
// integration tests runs | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpy.java
// public final static String DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME = "JENKINS_MAVEN_AGENT_DISABLED";
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/InvokerStartExecutionHandler.java
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import static org.jenkinsci.plugins.pipeline.maven.eventspy.JenkinsMavenEventSpy.DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.execution.ExecutionEvent;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* Handler to alter the
* <code>org.apache.maven.plugins:maven-invoker-plugin:run</code> goal : it will
* append the <code>JENKINS_MAVEN_AGENT_DISABLED</code> (set to
* <code>true</code>) to the environment.
* <p>
* Thus our spy will not run during Invoker integration tests, to avoid
* recording integration tests artifacts and dependencies.
*
* @author <a href="mailto:benoit.guerin1@free.fr">Benoit Guérin</a>
*
*/
public class InvokerStartExecutionHandler extends AbstractExecutionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
public InvokerStartExecutionHandler(final MavenEventReporter reporter) {
super(reporter);
}
@Override
@Nullable
protected ExecutionEvent.Type getSupportedType() {
return ExecutionEvent.Type.MojoStarted;
}
@Nullable
@Override
protected String getSupportedPluginGoal() {
return "org.apache.maven.plugins:maven-invoker-plugin:run";
}
@NonNull
@Override
protected List<String> getConfigurationParametersToReport(final ExecutionEvent executionEvent) {
return new ArrayList<String>();
}
@Override
public boolean _handle(final ExecutionEvent executionEvent) {
final boolean result = super._handle(executionEvent);
logger.debug("[jenkins-event-spy] Start of goal " + getSupportedPluginGoal() + ", disabling spy in IT tests.");
// First retrieve the "environmentVariables" configuration of the captured Mojo
Xpp3Dom env = executionEvent.getMojoExecution().getConfiguration().getChild("environmentVariables");
if (env == null) {
// if the mojo does not have such a configuration, create an empty one
env = new Xpp3Dom("environmentVariables");
executionEvent.getMojoExecution().getConfiguration().addChild(env);
}
// Finally, adding our environment variable to disable our spy during the
// integration tests runs | Xpp3Dom disableSpy = new Xpp3Dom(DISABLE_MAVEN_EVENT_SPY_ENVIRONMENT_VARIABLE_NAME); |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/JGivenTestsPublisher.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.StreamBuildListener;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.jgiven.JgivenReportGenerator;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.MavenPublisher;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.kohsuke.stapler.DataBoundConstructor;
import org.w3c.dom.Element;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.jenkinsci.plugins.pipeline.maven.publishers.DependenciesLister.listDependencies; | /*
* The MIT License Copyright (c) 2016, CloudBees, Inc. Permission is hereby
* granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions: The above copyright notice and this
* permission notice shall be included in all copies or substantial portions of
* the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.publishers;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JGivenTestsPublisher extends MavenPublisher {
public static final String REPORTS_DIR = "jgiven-reports";
private static final Logger LOGGER = Logger.getLogger(JGivenTestsPublisher.class.getName());
private static final long serialVersionUID = 1L;
@DataBoundConstructor
public JGivenTestsPublisher() {
}
@Override
public void process(@Nonnull final StepContext context, @Nonnull final Element mavenSpyLogsElt)
throws IOException, InterruptedException {
TaskListener listener = context.get(TaskListener.class);
if (listener == null) {
LOGGER.warning("TaskListener is NULL, default to stderr");
listener = new StreamBuildListener((OutputStream) System.err);
}
final FilePath workspace = context.get(FilePath.class);
final Run run = context.get(Run.class);
final Launcher launcher = context.get(Launcher.class);
try {
Class.forName("org.jenkinsci.plugins.jgiven.JgivenReportGenerator");
} catch (final ClassNotFoundException e) {
listener.getLogger().print("[withMaven] jgivenPublisher - Jenkins ");
listener.hyperlink("https://wiki.jenkins.io/display/JENKINS/JGiven+Plugin", "JGiven Plugin");
listener.getLogger().println(" not found, do not archive jgiven reports.");
return;
}
boolean foundJGivenDependency = false; | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/JGivenTestsPublisher.java
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.StreamBuildListener;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.jgiven.JgivenReportGenerator;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.MavenPublisher;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.kohsuke.stapler.DataBoundConstructor;
import org.w3c.dom.Element;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.jenkinsci.plugins.pipeline.maven.publishers.DependenciesLister.listDependencies;
/*
* The MIT License Copyright (c) 2016, CloudBees, Inc. Permission is hereby
* granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions: The above copyright notice and this
* permission notice shall be included in all copies or substantial portions of
* the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.publishers;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JGivenTestsPublisher extends MavenPublisher {
public static final String REPORTS_DIR = "jgiven-reports";
private static final Logger LOGGER = Logger.getLogger(JGivenTestsPublisher.class.getName());
private static final long serialVersionUID = 1L;
@DataBoundConstructor
public JGivenTestsPublisher() {
}
@Override
public void process(@Nonnull final StepContext context, @Nonnull final Element mavenSpyLogsElt)
throws IOException, InterruptedException {
TaskListener listener = context.get(TaskListener.class);
if (listener == null) {
LOGGER.warning("TaskListener is NULL, default to stderr");
listener = new StreamBuildListener((OutputStream) System.err);
}
final FilePath workspace = context.get(FilePath.class);
final Run run = context.get(Run.class);
final Launcher launcher = context.get(Launcher.class);
try {
Class.forName("org.jenkinsci.plugins.jgiven.JgivenReportGenerator");
} catch (final ClassNotFoundException e) {
listener.getLogger().print("[withMaven] jgivenPublisher - Jenkins ");
listener.hyperlink("https://wiki.jenkins.io/display/JENKINS/JGiven+Plugin", "JGiven Plugin");
listener.getLogger().println(" not found, do not archive jgiven reports.");
return;
}
boolean foundJGivenDependency = false; | List<MavenDependency> dependencies = listDependencies(mavenSpyLogsElt, LOGGER); |
jenkinsci/pipeline-maven-plugin | maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpyDisablementTest.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
| import org.junit.Test;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import org.apache.maven.eventspy.EventSpy;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.hamcrest.CoreMatchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.DevNullMavenEventReporter;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy;
/**
* Test how to disable the Maven Event Spy
*
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JenkinsMavenEventSpyDisablementTest {
@Test
public void when_disabled_maven_event_spy_must_use_the_dev_null_reporter() throws Exception {
JenkinsMavenEventSpy spy = new JenkinsMavenEventSpy() {
@Override
protected boolean isEventSpyDisabled() {
return true;
}
};
assertThat(spy.getReporter(), CoreMatchers.nullValue());
spy.init(new EventSpy.Context() {
@Override
public Map<String, Object> getData() {
return new HashMap<String, Object>();
}
});
assertThat(spy.getReporter(), CoreMatchers.instanceOf(DevNullMavenEventReporter.class));
assertThat(spy.disabled, CoreMatchers.is(true));
}
@Test
public void when_disabled_maven_event_spy_must_not_call_reporter() throws Exception { | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
// Path: maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpyDisablementTest.java
import org.junit.Test;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import org.apache.maven.eventspy.EventSpy;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.hamcrest.CoreMatchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.DevNullMavenEventReporter;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy;
/**
* Test how to disable the Maven Event Spy
*
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JenkinsMavenEventSpyDisablementTest {
@Test
public void when_disabled_maven_event_spy_must_use_the_dev_null_reporter() throws Exception {
JenkinsMavenEventSpy spy = new JenkinsMavenEventSpy() {
@Override
protected boolean isEventSpyDisabled() {
return true;
}
};
assertThat(spy.getReporter(), CoreMatchers.nullValue());
spy.init(new EventSpy.Context() {
@Override
public Map<String, Object> getData() {
return new HashMap<String, Object>();
}
});
assertThat(spy.getReporter(), CoreMatchers.instanceOf(DevNullMavenEventReporter.class));
assertThat(spy.disabled, CoreMatchers.is(true));
}
@Test
public void when_disabled_maven_event_spy_must_not_call_reporter() throws Exception { | MavenEventReporter reporterMustNeverBeInvoked = new MavenEventReporter() { |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/AbstractPipelineMavenPluginDao.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
//
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/util/ClassUtils.java
// public class ClassUtils {
//
// @Nullable
// public static InputStream getResourceAsStream(@Nonnull String resourcePath) {
// InputStream result = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
// if(result == null) {
// result = ClassUtils.class.getClassLoader().getResourceAsStream(resourcePath);
// }
// return result;
// }
//
// }
| import hudson.model.Item;
import hudson.model.Result;
import hudson.model.Run;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.h2.api.ErrorCode;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.db.migration.MigrationStep;
import org.jenkinsci.plugins.pipeline.maven.util.ClassUtils;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeIoException;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeSqlException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger; | initializeDatabase();
testDatabase();
}
protected abstract void registerJdbcDriver();
@Override
public void recordDependency(String jobFullName, int buildNumber, String groupId, String artifactId, String version, String type, String scope, boolean ignoreUpstreamTriggers, String classifier) {
LOGGER.log(Level.FINE, "recordDependency({0}#{1}, {2}:{3}:{4}:{5}, {6}, ignoreUpstreamTriggers:{7}})",
new Object[]{jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers});
long buildPrimaryKey = getOrCreateBuildPrimaryKey(jobFullName, buildNumber);
long artifactPrimaryKey = getOrCreateArtifactPrimaryKey(groupId, artifactId, version, type, classifier);
try (Connection cnn = ds.getConnection()) {
cnn.setAutoCommit(false);
try (PreparedStatement stmt = cnn.prepareStatement("INSERT INTO MAVEN_DEPENDENCY(ARTIFACT_ID, BUILD_ID, SCOPE, IGNORE_UPSTREAM_TRIGGERS) VALUES (?, ?, ?, ?)")) {
stmt.setLong(1, artifactPrimaryKey);
stmt.setLong(2, buildPrimaryKey);
stmt.setString(3, scope);
stmt.setBoolean(4, ignoreUpstreamTriggers);
stmt.execute();
}
cnn.commit();
} catch (SQLException e) {
throw new RuntimeSqlException(e);
}
}
@Nonnull
@Override | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
//
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/util/ClassUtils.java
// public class ClassUtils {
//
// @Nullable
// public static InputStream getResourceAsStream(@Nonnull String resourcePath) {
// InputStream result = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
// if(result == null) {
// result = ClassUtils.class.getClassLoader().getResourceAsStream(resourcePath);
// }
// return result;
// }
//
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/AbstractPipelineMavenPluginDao.java
import hudson.model.Item;
import hudson.model.Result;
import hudson.model.Run;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.h2.api.ErrorCode;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.db.migration.MigrationStep;
import org.jenkinsci.plugins.pipeline.maven.util.ClassUtils;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeIoException;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeSqlException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
initializeDatabase();
testDatabase();
}
protected abstract void registerJdbcDriver();
@Override
public void recordDependency(String jobFullName, int buildNumber, String groupId, String artifactId, String version, String type, String scope, boolean ignoreUpstreamTriggers, String classifier) {
LOGGER.log(Level.FINE, "recordDependency({0}#{1}, {2}:{3}:{4}:{5}, {6}, ignoreUpstreamTriggers:{7}})",
new Object[]{jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers});
long buildPrimaryKey = getOrCreateBuildPrimaryKey(jobFullName, buildNumber);
long artifactPrimaryKey = getOrCreateArtifactPrimaryKey(groupId, artifactId, version, type, classifier);
try (Connection cnn = ds.getConnection()) {
cnn.setAutoCommit(false);
try (PreparedStatement stmt = cnn.prepareStatement("INSERT INTO MAVEN_DEPENDENCY(ARTIFACT_ID, BUILD_ID, SCOPE, IGNORE_UPSTREAM_TRIGGERS) VALUES (?, ?, ?, ?)")) {
stmt.setLong(1, artifactPrimaryKey);
stmt.setLong(2, buildPrimaryKey);
stmt.setString(3, scope);
stmt.setBoolean(4, ignoreUpstreamTriggers);
stmt.execute();
}
cnn.commit();
} catch (SQLException e) {
throw new RuntimeSqlException(e);
}
}
@Nonnull
@Override | public List<MavenDependency> listDependencies(@Nonnull String jobFullName, int buildNumber) { |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/AbstractPipelineMavenPluginDao.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
//
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/util/ClassUtils.java
// public class ClassUtils {
//
// @Nullable
// public static InputStream getResourceAsStream(@Nonnull String resourcePath) {
// InputStream result = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
// if(result == null) {
// result = ClassUtils.class.getClassLoader().getResourceAsStream(resourcePath);
// }
// return result;
// }
//
// }
| import hudson.model.Item;
import hudson.model.Result;
import hudson.model.Run;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.h2.api.ErrorCode;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.db.migration.MigrationStep;
import org.jenkinsci.plugins.pipeline.maven.util.ClassUtils;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeIoException;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeSqlException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger; | try (PreparedStatement stmt = cnn.prepareStatement("INSERT INTO MAVEN_ARTIFACT(GROUP_ID, ARTIFACT_ID, VERSION, TYPE, CLASSIFIER) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, groupId);
stmt.setString(2, artifactId);
stmt.setString(3, version);
stmt.setString(4, type);
stmt.setString(5, classifier);
stmt.execute();
artifactPrimaryKey = getGeneratedPrimaryKey(stmt, "ID");
}
}
cnn.commit();
return artifactPrimaryKey;
} catch (SQLException e) {
throw new RuntimeSqlException(e);
}
}
protected synchronized void initializeDatabase() {
try (Connection cnn = ds.getConnection()) {
cnn.setAutoCommit(false);
int initialSchemaVersion = getSchemaVersion(cnn);
LOGGER.log(Level.FINE, "Initialise database. Current schema version: {0}", new Object[]{initialSchemaVersion});
NumberFormat numberFormat = new DecimalFormat("00");
int idx = initialSchemaVersion;
while (true) {
idx++;
String sqlScriptPath = "sql/" + getJdbcScheme() + "/" + numberFormat.format(idx) + "_migration.sql"; | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
//
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/util/ClassUtils.java
// public class ClassUtils {
//
// @Nullable
// public static InputStream getResourceAsStream(@Nonnull String resourcePath) {
// InputStream result = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
// if(result == null) {
// result = ClassUtils.class.getClassLoader().getResourceAsStream(resourcePath);
// }
// return result;
// }
//
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/AbstractPipelineMavenPluginDao.java
import hudson.model.Item;
import hudson.model.Result;
import hudson.model.Run;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.h2.api.ErrorCode;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.db.migration.MigrationStep;
import org.jenkinsci.plugins.pipeline.maven.util.ClassUtils;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeIoException;
import org.jenkinsci.plugins.pipeline.maven.util.RuntimeSqlException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
try (PreparedStatement stmt = cnn.prepareStatement("INSERT INTO MAVEN_ARTIFACT(GROUP_ID, ARTIFACT_ID, VERSION, TYPE, CLASSIFIER) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, groupId);
stmt.setString(2, artifactId);
stmt.setString(3, version);
stmt.setString(4, type);
stmt.setString(5, classifier);
stmt.execute();
artifactPrimaryKey = getGeneratedPrimaryKey(stmt, "ID");
}
}
cnn.commit();
return artifactPrimaryKey;
} catch (SQLException e) {
throw new RuntimeSqlException(e);
}
}
protected synchronized void initializeDatabase() {
try (Connection cnn = ds.getConnection()) {
cnn.setAutoCommit(false);
int initialSchemaVersion = getSchemaVersion(cnn);
LOGGER.log(Level.FINE, "Initialise database. Current schema version: {0}", new Object[]{initialSchemaVersion});
NumberFormat numberFormat = new DecimalFormat("00");
int idx = initialSchemaVersion;
while (true) {
idx++;
String sqlScriptPath = "sql/" + getJdbcScheme() + "/" + numberFormat.format(idx) + "_migration.sql"; | InputStream sqlScriptInputStream = ClassUtils.getResourceAsStream(sqlScriptPath); |
jenkinsci/pipeline-maven-plugin | maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/DependencyResolutionResultHandler.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
| import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.maven.project.DependencyResolutionResult;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.graph.Dependency;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class DependencyResolutionResultHandler extends AbstractMavenEventHandler<DependencyResolutionResult> {
/**
* Scope of the MAven dependencies that we dump<p/>
* <p>
* Standard Maven scopes: compile, provided, runtime, test, system and import
*
* @See <a href="https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope">Maven - Dependency Scopes</a>
* @see Dependency#getScope()
*/
private Set<String> includedScopes = new HashSet<String>(Arrays.asList("compile", "provided", "test"));
private boolean includeSnapshots = true;
private boolean includeReleases = true;
| // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/DependencyResolutionResultHandler.java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.maven.project.DependencyResolutionResult;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.graph.Dependency;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class DependencyResolutionResultHandler extends AbstractMavenEventHandler<DependencyResolutionResult> {
/**
* Scope of the MAven dependencies that we dump<p/>
* <p>
* Standard Maven scopes: compile, provided, runtime, test, system and import
*
* @See <a href="https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope">Maven - Dependency Scopes</a>
* @see Dependency#getScope()
*/
private Set<String> includedScopes = new HashSet<String>(Arrays.asList("compile", "provided", "test"));
private boolean includeSnapshots = true;
private boolean includeReleases = true;
| public DependencyResolutionResultHandler(MavenEventReporter reporter) { |
jenkinsci/pipeline-maven-plugin | maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/AbstractMavenEventHandlerTest.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
| import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.hamcrest.Matchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import static org.hamcrest.MatcherAssert.assertThat; | package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class AbstractMavenEventHandlerTest {
@Test
public void test_getMavenFlattenPluginFlattenedPomFilename_nameDefinedAtTheExecutionLevel() throws Exception {
test_getMavenFlattenPluginFlattenedPomFilename(
"org/jenkinsci/plugins/pipeline/maven/eventspy/pom-flatten-plugin-flattenedPomFilename.xml",
"${project.artifactId}-${project.version}.pom");
}
@Test
public void test_getMavenFlattenPluginFlattenedPomFilename_nameDefinedAtThePluginLevel() throws Exception {
test_getMavenFlattenPluginFlattenedPomFilename(
"org/jenkinsci/plugins/pipeline/maven/eventspy/pom-flatten-plugin-flattenedPomFilename2.xml",
"${project.artifactId}-${project.version}.flatten-pom");
}
@Test
public void test_getMavenFlattenPluginFlattenedPomFilename_nameNotDefined() throws Exception {
test_getMavenFlattenPluginFlattenedPomFilename(
"org/jenkinsci/plugins/pipeline/maven/eventspy/pom.xml",
null);
}
protected void test_getMavenFlattenPluginFlattenedPomFilename(String pomFile, String expected) throws IOException, XmlPullParserException {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(pomFile);
Model mavenProjectModel = new MavenXpp3Reader().read(in);
MavenProject mavenProject = new MavenProject(mavenProjectModel); | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
// Path: maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/AbstractMavenEventHandlerTest.java
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.hamcrest.Matchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import static org.hamcrest.MatcherAssert.assertThat;
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class AbstractMavenEventHandlerTest {
@Test
public void test_getMavenFlattenPluginFlattenedPomFilename_nameDefinedAtTheExecutionLevel() throws Exception {
test_getMavenFlattenPluginFlattenedPomFilename(
"org/jenkinsci/plugins/pipeline/maven/eventspy/pom-flatten-plugin-flattenedPomFilename.xml",
"${project.artifactId}-${project.version}.pom");
}
@Test
public void test_getMavenFlattenPluginFlattenedPomFilename_nameDefinedAtThePluginLevel() throws Exception {
test_getMavenFlattenPluginFlattenedPomFilename(
"org/jenkinsci/plugins/pipeline/maven/eventspy/pom-flatten-plugin-flattenedPomFilename2.xml",
"${project.artifactId}-${project.version}.flatten-pom");
}
@Test
public void test_getMavenFlattenPluginFlattenedPomFilename_nameNotDefined() throws Exception {
test_getMavenFlattenPluginFlattenedPomFilename(
"org/jenkinsci/plugins/pipeline/maven/eventspy/pom.xml",
null);
}
protected void test_getMavenFlattenPluginFlattenedPomFilename(String pomFile, String expected) throws IOException, XmlPullParserException {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(pomFile);
Model mavenProjectModel = new MavenXpp3Reader().read(in);
MavenProject mavenProject = new MavenProject(mavenProjectModel); | AbstractMavenEventHandler mavenEventHandler = new AbstractMavenEventHandler(new OutputStreamEventReporter(System.err)) { |
jenkinsci/pipeline-maven-plugin | maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/AbstractMavenEventHandler.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
| import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.model.Build;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.jenkinsci.plugins.pipeline.maven.eventspy.RuntimeIOException;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public abstract class AbstractMavenEventHandler<E> implements MavenEventHandler<E> {
protected final Logger logger = LoggerFactory.getLogger(getClass());
| // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/AbstractMavenEventHandler.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.model.Build;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.jenkinsci.plugins.pipeline.maven.eventspy.RuntimeIOException;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public abstract class AbstractMavenEventHandler<E> implements MavenEventHandler<E> {
protected final Logger logger = LoggerFactory.getLogger(getClass());
| protected final MavenEventReporter reporter; |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginNullDao.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Collections; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.dao;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class PipelineMavenPluginNullDao implements PipelineMavenPluginDao {
private static Logger LOGGER = Logger.getLogger(PipelineMavenPluginNullDao.class.getName());
@Override
public void recordDependency(String jobFullName, int buildNumber, String groupId, String artifactId, String version, String type, String scope, boolean ignoreUpstreamTriggers, String classifier) {
LOGGER.log(Level.INFO, "recordDependency({0}#{1}, {2}:{3}:{4}:{5}, {6}, ignoreUpstreamTriggers:{7}})",
new Object[]{jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers});
}
@Nonnull
@Override | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginNullDao.java
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Collections;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.dao;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class PipelineMavenPluginNullDao implements PipelineMavenPluginDao {
private static Logger LOGGER = Logger.getLogger(PipelineMavenPluginNullDao.class.getName());
@Override
public void recordDependency(String jobFullName, int buildNumber, String groupId, String artifactId, String version, String type, String scope, boolean ignoreUpstreamTriggers, String classifier) {
LOGGER.log(Level.INFO, "recordDependency({0}#{1}, {2}:{3}:{4}:{5}, {6}, ignoreUpstreamTriggers:{7}})",
new Object[]{jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers});
}
@Nonnull
@Override | public List<MavenDependency> listDependencies(@Nonnull String jobFullName, int buildNumber) { |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/AbstractPipelineMavenPluginDaoDecorator.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedSet; | package org.jenkinsci.plugins.pipeline.maven.dao;
public abstract class AbstractPipelineMavenPluginDaoDecorator implements PipelineMavenPluginDao {
protected final PipelineMavenPluginDao delegate;
public AbstractPipelineMavenPluginDaoDecorator(@Nonnull PipelineMavenPluginDao delegate) {
this.delegate = delegate;
}
@Override
public void recordDependency(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String scope, boolean ignoreUpstreamTriggers, String classifier) {
delegate.recordDependency(jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers, classifier);
}
@Override
public void recordParentProject(@Nonnull String jobFullName, int buildNumber, @Nonnull String parentGroupId, @Nonnull String parentArtifactId, @Nonnull String parentVersion, boolean ignoreUpstreamTriggers) {
delegate.recordParentProject(jobFullName, buildNumber, parentGroupId, parentArtifactId, parentVersion, ignoreUpstreamTriggers);
}
@Override
public void recordGeneratedArtifact(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String baseVersion, @Nullable String repositoryUrl, boolean skipDownstreamTriggers, String extension, String classifier) {
delegate.recordGeneratedArtifact(jobFullName, buildNumber, groupId, artifactId, version, type, baseVersion, repositoryUrl, skipDownstreamTriggers, extension, classifier);
}
@Override
public void recordBuildUpstreamCause(String upstreamJobName, int upstreamBuildNumber, String downstreamJobName, int downstreamBuildNumber) {
delegate.recordBuildUpstreamCause(upstreamJobName, upstreamBuildNumber, downstreamJobName, downstreamBuildNumber);
}
@Nonnull
@Override | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/AbstractPipelineMavenPluginDaoDecorator.java
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
package org.jenkinsci.plugins.pipeline.maven.dao;
public abstract class AbstractPipelineMavenPluginDaoDecorator implements PipelineMavenPluginDao {
protected final PipelineMavenPluginDao delegate;
public AbstractPipelineMavenPluginDaoDecorator(@Nonnull PipelineMavenPluginDao delegate) {
this.delegate = delegate;
}
@Override
public void recordDependency(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String scope, boolean ignoreUpstreamTriggers, String classifier) {
delegate.recordDependency(jobFullName, buildNumber, groupId, artifactId, version, type, scope, ignoreUpstreamTriggers, classifier);
}
@Override
public void recordParentProject(@Nonnull String jobFullName, int buildNumber, @Nonnull String parentGroupId, @Nonnull String parentArtifactId, @Nonnull String parentVersion, boolean ignoreUpstreamTriggers) {
delegate.recordParentProject(jobFullName, buildNumber, parentGroupId, parentArtifactId, parentVersion, ignoreUpstreamTriggers);
}
@Override
public void recordGeneratedArtifact(@Nonnull String jobFullName, int buildNumber, @Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version, @Nonnull String type, @Nonnull String baseVersion, @Nullable String repositoryUrl, boolean skipDownstreamTriggers, String extension, String classifier) {
delegate.recordGeneratedArtifact(jobFullName, buildNumber, groupId, artifactId, version, type, baseVersion, repositoryUrl, skipDownstreamTriggers, extension, classifier);
}
@Override
public void recordBuildUpstreamCause(String upstreamJobName, int upstreamBuildNumber, String downstreamJobName, int downstreamBuildNumber) {
delegate.recordBuildUpstreamCause(upstreamJobName, upstreamBuildNumber, downstreamJobName, downstreamBuildNumber);
}
@Nonnull
@Override | public List<MavenDependency> listDependencies(@Nonnull String jobFullName, int buildNumber) { |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginDaoAbstractTest.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import hudson.model.Result;
import org.hamcrest.Matchers;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.util.SqlTestsUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.in; | // AFTER DELETE FIRST
SqlTestsUtils.dump("select * from JENKINS_JOB", ds, System.out);
dao.deleteBuild("my-pipeline", 3);
System.out.println("AFTER DELETE LAST BUILD");
SqlTestsUtils.dump("select * from JENKINS_JOB", ds, System.out);
}
@Test
public void record_one_dependency() throws Exception {
dao.recordDependency("my-pipeline", 1, "com.h2.database", "h2", "1.4.196", "jar", "compile", false, null);
SqlTestsUtils.dump("select * from JENKINS_BUILD LEFT OUTER JOIN JENKINS_JOB ON JENKINS_BUILD.JOB_ID = JENKINS_JOB.ID", ds, System.out);
SqlTestsUtils.dump("select * from MAVEN_ARTIFACT", ds, System.out);
SqlTestsUtils.dump("select * from MAVEN_DEPENDENCY", ds, System.out);
assertThat(
SqlTestsUtils.countRows("select * from JENKINS_BUILD", ds),
is(1));
assertThat(
SqlTestsUtils.countRows("select * from MAVEN_ARTIFACT", ds),
is(1));
assertThat(
SqlTestsUtils.countRows("select * from MAVEN_DEPENDENCY", ds),
is(1));
| // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/test/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginDaoAbstractTest.java
import hudson.model.Result;
import org.hamcrest.Matchers;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.util.SqlTestsUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.in;
// AFTER DELETE FIRST
SqlTestsUtils.dump("select * from JENKINS_JOB", ds, System.out);
dao.deleteBuild("my-pipeline", 3);
System.out.println("AFTER DELETE LAST BUILD");
SqlTestsUtils.dump("select * from JENKINS_JOB", ds, System.out);
}
@Test
public void record_one_dependency() throws Exception {
dao.recordDependency("my-pipeline", 1, "com.h2.database", "h2", "1.4.196", "jar", "compile", false, null);
SqlTestsUtils.dump("select * from JENKINS_BUILD LEFT OUTER JOIN JENKINS_JOB ON JENKINS_BUILD.JOB_ID = JENKINS_JOB.ID", ds, System.out);
SqlTestsUtils.dump("select * from MAVEN_ARTIFACT", ds, System.out);
SqlTestsUtils.dump("select * from MAVEN_DEPENDENCY", ds, System.out);
assertThat(
SqlTestsUtils.countRows("select * from JENKINS_BUILD", ds),
is(1));
assertThat(
SqlTestsUtils.countRows("select * from MAVEN_ARTIFACT", ds),
is(1));
assertThat(
SqlTestsUtils.countRows("select * from MAVEN_DEPENDENCY", ds),
is(1));
| List<MavenDependency> mavenDependencies = dao.listDependencies("my-pipeline", 1); |
jenkinsci/pipeline-maven-plugin | maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/DeployDeployFileExecutionHandlerTest.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.hamcrest.Matchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; | package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:r.schleuse@gmail.com">René Schleusner</a>
*/
public class DeployDeployFileExecutionHandlerTest {
DeployDeployFileExecutionHandler handler;
MavenProject project;
ByteArrayOutputStream eventReportOutputStream; | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
// Path: maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/handler/DeployDeployFileExecutionHandlerTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.hamcrest.Matchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
package org.jenkinsci.plugins.pipeline.maven.eventspy.handler;
/**
* @author <a href="mailto:r.schleuse@gmail.com">René Schleusner</a>
*/
public class DeployDeployFileExecutionHandlerTest {
DeployDeployFileExecutionHandler handler;
MavenProject project;
ByteArrayOutputStream eventReportOutputStream; | OutputStreamEventReporter reporter; |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/util/XmlUtils.java | // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
| import hudson.FilePath;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.MavenSpyLogProcessor;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.util;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class XmlUtils {
private static final Logger LOGGER = Logger.getLogger(XmlUtils.class.getName());
public static MavenArtifact newMavenArtifact(Element artifactElt) {
MavenArtifact mavenArtifact = new MavenArtifact();
loadMavenArtifact(artifactElt, mavenArtifact);
return mavenArtifact;
}
| // Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/MavenDependency.java
// public class MavenDependency extends MavenArtifact {
//
// private String scope;
// public boolean optional;
//
// @Nonnull
// public String getScope() {
// return scope == null ? "compile" : scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope == null || scope.isEmpty() ? null : scope;
// }
//
// @Override
// public String toString() {
// return "MavenDependency{" +
// getGroupId() + ":" +
// getArtifactId() + ":" +
// getType() +
// (getClassifier() == null ? "" : ":" + getClassifier()) + ":" +
// getBaseVersion() + ", " +
// "scope: " + scope + ", " +
// " optional: " + optional +
// " version: " + getVersion() +
// " snapshot: " + isSnapshot() +
// (getFile() == null ? "" : " " + getFile()) +
// '}';
// }
//
// public MavenArtifact asMavenArtifact() {
// MavenArtifact result = new MavenArtifact();
//
// result.setGroupId(getGroupId());
// result.setArtifactId(getArtifactId());
// result.setVersion(getVersion());
// result.setBaseVersion(getBaseVersion());
// result.setType(getType());
// result.setClassifier(getClassifier());
// result.setExtension(getExtension());
// result.setFile(getFile());
// result.setSnapshot(isSnapshot());
//
// return result;
// }
//
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), optional, scope);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// MavenDependency other = (MavenDependency) obj;
// if (optional != other.optional)
// return false;
// if (scope == null) {
// return other.scope == null;
// } else return scope.equals(other.scope);
// }
// }
// Path: jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/util/XmlUtils.java
import hudson.FilePath;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.pipeline.maven.MavenArtifact;
import org.jenkinsci.plugins.pipeline.maven.MavenDependency;
import org.jenkinsci.plugins.pipeline.maven.MavenSpyLogProcessor;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.util;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class XmlUtils {
private static final Logger LOGGER = Logger.getLogger(XmlUtils.class.getName());
public static MavenArtifact newMavenArtifact(Element artifactElt) {
MavenArtifact mavenArtifact = new MavenArtifact();
loadMavenArtifact(artifactElt, mavenArtifact);
return mavenArtifact;
}
| public static MavenDependency newMavenDependency(Element dependencyElt) { |
jenkinsci/pipeline-maven-plugin | maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpyTest.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
| import org.apache.maven.eventspy.EventSpy;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.hamcrest.CoreMatchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JenkinsMavenEventSpyTest {
JenkinsMavenEventSpy spy; | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
// Path: maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpyTest.java
import org.apache.maven.eventspy.EventSpy;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.hamcrest.CoreMatchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JenkinsMavenEventSpyTest {
JenkinsMavenEventSpy spy; | MavenEventReporter reporter; |
jenkinsci/pipeline-maven-plugin | maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpyTest.java | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
| import org.apache.maven.eventspy.EventSpy;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.hamcrest.CoreMatchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; | /*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JenkinsMavenEventSpyTest {
JenkinsMavenEventSpy spy;
MavenEventReporter reporter;
StringWriter writer = new StringWriter();
MavenProject project;
@Before
public void before() throws Exception { | // Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/MavenEventReporter.java
// public interface MavenEventReporter {
// void print(Object message);
//
// void print(Xpp3Dom element);
//
// /**
// * Close the reporter at the end of the Maven execution. No call to
// * {@link #print(Object)} or {@link #print(Xpp3Dom)} will be made after the
// * invocation of this method.
// *
// * @see EventSpy#close()
// */
// void close();
// }
//
// Path: maven-spy/src/main/java/org/jenkinsci/plugins/pipeline/maven/eventspy/reporter/OutputStreamEventReporter.java
// public class OutputStreamEventReporter implements MavenEventReporter {
//
// final PrintWriter out;
// final XMLWriter xmlWriter;
//
// public OutputStreamEventReporter(OutputStream out) {
// this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
// }
//
// public OutputStreamEventReporter(Writer out) {
// if (out instanceof PrintWriter) {
// this.out = (PrintWriter) out;
// } else {
// this.out = new PrintWriter(out, true);
// }
// this.xmlWriter = new PrettyPrintXMLWriter(out);
// xmlWriter.startElement("mavenExecution");
//
// }
//
// @Override
// public synchronized void print(Object message) {
// String comment = new Timestamp(System.currentTimeMillis()) + " - " + message;
// XmlWriterUtil.writeComment(xmlWriter, comment);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void print(Xpp3Dom element) {
// Xpp3DomWriter.write(xmlWriter, element);
// XmlWriterUtil.writeLineBreak(xmlWriter);
//
// out.flush();
// }
//
// @Override
// public synchronized void close() {
// xmlWriter.endElement();
// out.flush();
// }
// }
// Path: maven-spy/src/test/java/org/jenkinsci/plugins/pipeline/maven/eventspy/JenkinsMavenEventSpyTest.java
import org.apache.maven.eventspy.EventSpy;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.hamcrest.CoreMatchers;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.MavenEventReporter;
import org.jenkinsci.plugins.pipeline.maven.eventspy.reporter.OutputStreamEventReporter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.pipeline.maven.eventspy;
/**
* @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
*/
public class JenkinsMavenEventSpyTest {
JenkinsMavenEventSpy spy;
MavenEventReporter reporter;
StringWriter writer = new StringWriter();
MavenProject project;
@Before
public void before() throws Exception { | reporter = new OutputStreamEventReporter(writer); |
9miao/CartoonHouse | DMZJ/proj.android/src/com/dmzj/manhua/openapi/OpenApiHelper.java | // Path: DMZJ/proj.android/src/com/dmzj/manhua/HelloCpp.java
// public class HelloCpp extends Cocos2dxActivity{
//
//
// //推送的json数据
// public static final String INTENT_EXTRA_TITLE = "intent_extra_title";
// public static final String INTENT_EXTRA_DESC = "intent_extra_desc";
// public static final String INTENT_EXTRA_PUSHMSG = "intent_extra_pushmsg";
//
// private static final String TAG = "HelloCpp";
//
// private Handler mDefaultHandler;
//
// private SinaOpenApi sinaAPI;
// private TencentOpenApi tencentAPI;
//
// private OpenApiHelper mOpenApiHelper;
//
//
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// WebViewCtrl.init(this);
// PhoneNet.getInstance().setContext(this);
// initWithApiKey();
// initEnviroment();
// AnalyticsHome.init(this);
//
// /***
// sinaAPI = new SinaOpenApi(HelloCpp.this);
// sinaAPI.getAccessToken();
// **/
//
// /***
// Handler mHandler = new Handler();
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// tencentAPI = new TencentOpenApi(HelloCpp.this);
// tencentAPI.getAccessToken();
// }
// }, 2000);
// **/
// checkPushInfo();
//
// }
//
//
// @Override
// protected void onNewIntent(Intent intent) {
//
// super.onNewIntent(intent);
// }
//
//
//
// private void initEnviroment(){
// mDefaultHandler = new Handler(){
// @Override
// public void handleMessage(Message msg) {
// onHandleMessage(msg);
// }
// };
// mOpenApiHelper = new OpenApiHelper(this);
// }
//
// public Cocos2dxGLSurfaceView onCreateView() {
// Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
// // HelloCpp should create stencil buffer
// glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
//
// return glSurfaceView;
// }
//
// static {
// System.loadLibrary("CrossApp_cpp");
// }
//
// private void onHandleMessage(Message msg){
// switch (msg.what) {
// // case OpenApiHelper.MSG_WHAT_PLAT_QQ:
// // tencentAPI = new TencentOpenApi(HelloCpp.this);
// // tencentAPI.getAccessToken();
// // break;
// // case OpenApiHelper.MSG_WHAT_PLAT_SINA:
// // sinaAPI = new SinaOpenApi(HelloCpp.this);
// // sinaAPI.getAccessToken();
// // break;
// // case SinaOpenApi.MSG_WHAT_SINATOKEN:
// // String token = AccessTokenKeeper.readAccessToken(HelloCpp.this).getToken();
// // OpenApiHelper.onTokenReturn(OpenApiHelper.PLAT_SINA, token ,AccessTokenKeeper.readAccessToken(HelloCpp.this).getUid());
// // break;
// // case TencentOpenApi.MSG_WHAT_QQTOKEN:
// // OpenApiHelper.onTokenReturn(OpenApiHelper.PLAT_QQ, tencentAPI.getmTencent().getQQToken().getAccessToken(),tencentAPI.getmTencent().getQQToken().getOpenId());
// // break;
// default:
// break;
// }
// }
//
// private void initWithApiKey() {
// // Push: 无账号初始化,用api key绑定
// if(!Utils.hasBind(getApplicationContext()))
// {
// PushManager.startWork(getApplicationContext(),
// PushConstants.LOGIN_TYPE_API_KEY,
// Utils.getMetaValue(HelloCpp.this, "api_key"));
// }
// }
//
//
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// super.onActivityResult(requestCode, resultCode, intent);
//
// // if (sinaAPI!=null) {
// // sinaAPI.getmSsoHandler().authorizeCallBack(requestCode, resultCode, intent);
// // }
// // if(tencentAPI!=null){
// // Log.d(TAG, "onActivityResult");
// // tencentAPI.onActivityResult(requestCode, resultCode, intent);
// // }
// }
//
//
// public Handler getmDefaultHandler() {
// return mDefaultHandler;
// }
//
// public void setmDefaultHandler(Handler mDefaultHandler) {
// this.mDefaultHandler = mDefaultHandler;
// }
//
//
// private void checkPushInfo(){
// if (getIntent().getStringExtra(INTENT_EXTRA_PUSHMSG)!=null) {
// MessagePushTool.onMessageObtain(HelloCpp.this, getIntent().getStringExtra(INTENT_EXTRA_TITLE),
// getIntent().getStringExtra(INTENT_EXTRA_DESC),
// getIntent().getStringExtra(INTENT_EXTRA_PUSHMSG));
// }
//
// }
//
//
// }
| import android.R.string;
import com.dmzj.manhua.HelloCpp; | package com.dmzj.manhua.openapi;
public class OpenApiHelper {
private static final String TAG = "OpenApiHelper";
/** QQ平台 */
public static final int PLAT_QQ = 0x1;
/** 新浪平台 */
public static final int PLAT_SINA = 0x2;
public static final int MSG_WHAT_PLAT_QQ = 0x10;
public static final int MSG_WHAT_PLAT_SINA = 0x11;
| // Path: DMZJ/proj.android/src/com/dmzj/manhua/HelloCpp.java
// public class HelloCpp extends Cocos2dxActivity{
//
//
// //推送的json数据
// public static final String INTENT_EXTRA_TITLE = "intent_extra_title";
// public static final String INTENT_EXTRA_DESC = "intent_extra_desc";
// public static final String INTENT_EXTRA_PUSHMSG = "intent_extra_pushmsg";
//
// private static final String TAG = "HelloCpp";
//
// private Handler mDefaultHandler;
//
// private SinaOpenApi sinaAPI;
// private TencentOpenApi tencentAPI;
//
// private OpenApiHelper mOpenApiHelper;
//
//
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// WebViewCtrl.init(this);
// PhoneNet.getInstance().setContext(this);
// initWithApiKey();
// initEnviroment();
// AnalyticsHome.init(this);
//
// /***
// sinaAPI = new SinaOpenApi(HelloCpp.this);
// sinaAPI.getAccessToken();
// **/
//
// /***
// Handler mHandler = new Handler();
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// tencentAPI = new TencentOpenApi(HelloCpp.this);
// tencentAPI.getAccessToken();
// }
// }, 2000);
// **/
// checkPushInfo();
//
// }
//
//
// @Override
// protected void onNewIntent(Intent intent) {
//
// super.onNewIntent(intent);
// }
//
//
//
// private void initEnviroment(){
// mDefaultHandler = new Handler(){
// @Override
// public void handleMessage(Message msg) {
// onHandleMessage(msg);
// }
// };
// mOpenApiHelper = new OpenApiHelper(this);
// }
//
// public Cocos2dxGLSurfaceView onCreateView() {
// Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
// // HelloCpp should create stencil buffer
// glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
//
// return glSurfaceView;
// }
//
// static {
// System.loadLibrary("CrossApp_cpp");
// }
//
// private void onHandleMessage(Message msg){
// switch (msg.what) {
// // case OpenApiHelper.MSG_WHAT_PLAT_QQ:
// // tencentAPI = new TencentOpenApi(HelloCpp.this);
// // tencentAPI.getAccessToken();
// // break;
// // case OpenApiHelper.MSG_WHAT_PLAT_SINA:
// // sinaAPI = new SinaOpenApi(HelloCpp.this);
// // sinaAPI.getAccessToken();
// // break;
// // case SinaOpenApi.MSG_WHAT_SINATOKEN:
// // String token = AccessTokenKeeper.readAccessToken(HelloCpp.this).getToken();
// // OpenApiHelper.onTokenReturn(OpenApiHelper.PLAT_SINA, token ,AccessTokenKeeper.readAccessToken(HelloCpp.this).getUid());
// // break;
// // case TencentOpenApi.MSG_WHAT_QQTOKEN:
// // OpenApiHelper.onTokenReturn(OpenApiHelper.PLAT_QQ, tencentAPI.getmTencent().getQQToken().getAccessToken(),tencentAPI.getmTencent().getQQToken().getOpenId());
// // break;
// default:
// break;
// }
// }
//
// private void initWithApiKey() {
// // Push: 无账号初始化,用api key绑定
// if(!Utils.hasBind(getApplicationContext()))
// {
// PushManager.startWork(getApplicationContext(),
// PushConstants.LOGIN_TYPE_API_KEY,
// Utils.getMetaValue(HelloCpp.this, "api_key"));
// }
// }
//
//
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// super.onActivityResult(requestCode, resultCode, intent);
//
// // if (sinaAPI!=null) {
// // sinaAPI.getmSsoHandler().authorizeCallBack(requestCode, resultCode, intent);
// // }
// // if(tencentAPI!=null){
// // Log.d(TAG, "onActivityResult");
// // tencentAPI.onActivityResult(requestCode, resultCode, intent);
// // }
// }
//
//
// public Handler getmDefaultHandler() {
// return mDefaultHandler;
// }
//
// public void setmDefaultHandler(Handler mDefaultHandler) {
// this.mDefaultHandler = mDefaultHandler;
// }
//
//
// private void checkPushInfo(){
// if (getIntent().getStringExtra(INTENT_EXTRA_PUSHMSG)!=null) {
// MessagePushTool.onMessageObtain(HelloCpp.this, getIntent().getStringExtra(INTENT_EXTRA_TITLE),
// getIntent().getStringExtra(INTENT_EXTRA_DESC),
// getIntent().getStringExtra(INTENT_EXTRA_PUSHMSG));
// }
//
// }
//
//
// }
// Path: DMZJ/proj.android/src/com/dmzj/manhua/openapi/OpenApiHelper.java
import android.R.string;
import com.dmzj.manhua.HelloCpp;
package com.dmzj.manhua.openapi;
public class OpenApiHelper {
private static final String TAG = "OpenApiHelper";
/** QQ平台 */
public static final int PLAT_QQ = 0x1;
/** 新浪平台 */
public static final int PLAT_SINA = 0x2;
public static final int MSG_WHAT_PLAT_QQ = 0x10;
public static final int MSG_WHAT_PLAT_SINA = 0x11;
| private static HelloCpp mActivity; |
9miao/CartoonHouse | DMZJ/proj.android/src/com/component/impl/VideoViewCtrl.java | // Path: DMZJ/proj.android/src/com/component/impl/VideoView.java
// public interface OnFinishListener {
// public void onVideoFinish();
// }
| import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsoluteLayout;
import com.component.impl.VideoView.OnFinishListener; | int margin = 0;
if ((float) width / height > 2.0 / 3.0) {
// 左右留边
margin = (int) ((width - ((2.0 * height) / 3.0)) / 2.0);
layout.setPadding(margin, 0, margin, 0);
} else if ((float) width / height < 2.0 / 3.0) {
// 上下留边
margin = (int) ((height - ((3.0 * width) / 2.0)) / 2.0);
layout.setPadding(0, margin, 0, margin);
}
context.addContentView(layout, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
public void play(final String filename, final boolean skipable) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
finished = false;
video = new VideoView(context);
video.setSkipable(skipable);
AssetFileDescriptor afd = context.getAssets().openFd(
filename);
video.setVideo(afd);
layout.addView(video);
video.setZOrderMediaOverlay(true);
| // Path: DMZJ/proj.android/src/com/component/impl/VideoView.java
// public interface OnFinishListener {
// public void onVideoFinish();
// }
// Path: DMZJ/proj.android/src/com/component/impl/VideoViewCtrl.java
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsoluteLayout;
import com.component.impl.VideoView.OnFinishListener;
int margin = 0;
if ((float) width / height > 2.0 / 3.0) {
// 左右留边
margin = (int) ((width - ((2.0 * height) / 3.0)) / 2.0);
layout.setPadding(margin, 0, margin, 0);
} else if ((float) width / height < 2.0 / 3.0) {
// 上下留边
margin = (int) ((height - ((3.0 * width) / 2.0)) / 2.0);
layout.setPadding(0, margin, 0, margin);
}
context.addContentView(layout, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
public void play(final String filename, final boolean skipable) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
finished = false;
video = new VideoView(context);
video.setSkipable(skipable);
AssetFileDescriptor afd = context.getAssets().openFd(
filename);
video.setVideo(afd);
layout.addView(video);
video.setZOrderMediaOverlay(true);
| video.setOnFinishListener(new OnFinishListener() { |
thejamesthomas/javabank | javabank-client/src/main/java/org/mbtest/javabank/Client.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
| import org.json.JSONArray;
import org.json.simple.parser.ParseException;
import org.mbtest.javabank.http.imposters.Imposter;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException; | public Client(String baseUrl) {
this.baseUrl = baseUrl;
}
public Client(String host, int port) {
this.baseUrl = String.format("http://%s:%d", host, port);
}
public String getBaseUrl() {
return baseUrl;
}
public boolean isMountebankRunning() {
try {
HttpResponse<JsonNode> response = Unirest.get(baseUrl).asJson();
return response.getStatus() == 200;
} catch (UnirestException e) {
return false;
}
}
public boolean isMountebankAllowingInjection() {
try {
HttpResponse<JsonNode> response = Unirest.get(baseUrl + "/config").asJson();
return response.getBody().getObject().getJSONObject("options").getBoolean("allowInjection");
} catch (UnirestException e) {
return false;
}
}
| // Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
// Path: javabank-client/src/main/java/org/mbtest/javabank/Client.java
import org.json.JSONArray;
import org.json.simple.parser.ParseException;
import org.mbtest.javabank.http.imposters.Imposter;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public Client(String baseUrl) {
this.baseUrl = baseUrl;
}
public Client(String host, int port) {
this.baseUrl = String.format("http://%s:%d", host, port);
}
public String getBaseUrl() {
return baseUrl;
}
public boolean isMountebankRunning() {
try {
HttpResponse<JsonNode> response = Unirest.get(baseUrl).asJson();
return response.getStatus() == 200;
} catch (UnirestException e) {
return false;
}
}
public boolean isMountebankAllowingInjection() {
try {
HttpResponse<JsonNode> response = Unirest.get(baseUrl + "/config").asJson();
return response.getBody().getObject().getJSONObject("options").getBoolean("allowInjection");
} catch (UnirestException e) {
return false;
}
}
| public int createImposter(Imposter imposter) { |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/ImposterParserTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
| import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.junit.Ignore;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.imposters.Imposter;
import static org.assertj.core.api.Assertions.assertThat; | package org.mbtest.javabank;
public class ImposterParserTest {
@Test
public void shouldParseJSONIntoImposter() throws ParseException { | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/ImposterParserTest.java
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.junit.Ignore;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.imposters.Imposter;
import static org.assertj.core.api.Assertions.assertThat;
package org.mbtest.javabank;
public class ImposterParserTest {
@Test
public void shouldParseJSONIntoImposter() throws ParseException { | Imposter expectedImposter = ImposterBuilder.anImposter().onPort(1234).build(); |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/ImposterParserTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
| import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.junit.Ignore;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.imposters.Imposter;
import static org.assertj.core.api.Assertions.assertThat; | package org.mbtest.javabank;
public class ImposterParserTest {
@Test
public void shouldParseJSONIntoImposter() throws ParseException { | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/ImposterParserTest.java
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.junit.Ignore;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.imposters.Imposter;
import static org.assertj.core.api.Assertions.assertThat;
package org.mbtest.javabank;
public class ImposterParserTest {
@Test
public void shouldParseJSONIntoImposter() throws ParseException { | Imposter expectedImposter = ImposterBuilder.anImposter().onPort(1234).build(); |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/fluent/IsBuilderTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
| import org.junit.Test;
import org.mbtest.javabank.http.responses.Is;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat; | package org.mbtest.javabank.fluent;
public class IsBuilderTest {
@Test
public void testBuildWithFileBody() throws Exception {
IsBuilder testSubject = new IsBuilder(null); | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/fluent/IsBuilderTest.java
import org.junit.Test;
import org.mbtest.javabank.http.responses.Is;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
package org.mbtest.javabank.fluent;
public class IsBuilderTest {
@Test
public void testBuildWithFileBody() throws Exception {
IsBuilder testSubject = new IsBuilder(null); | final Is is = testSubject.body(new File("src/test/resources/response.json")).build(); |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/fluent/InjectBuilderTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Inject.java
// public class Inject extends Response {
// private static final String INJECT = "inject";
//
// public Inject() {
// this.put(INJECT, "");
// }
//
// public Inject withFunction(String function) {
// this.put(INJECT, function);
// return this;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.http.responses.Inject;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock; | package org.mbtest.javabank.fluent;
public class InjectBuilderTest {
private InjectBuilder injectBuilder;
@Before
public void setUp() throws Exception {
injectBuilder = new InjectBuilder(mock(ResponseBuilder.class));
}
@Test
public void shouldBuildAnInjectWithAFunction() throws Exception {
String injection = "some function"; | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Inject.java
// public class Inject extends Response {
// private static final String INJECT = "inject";
//
// public Inject() {
// this.put(INJECT, "");
// }
//
// public Inject withFunction(String function) {
// this.put(INJECT, function);
// return this;
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/fluent/InjectBuilderTest.java
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.http.responses.Inject;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
package org.mbtest.javabank.fluent;
public class InjectBuilderTest {
private InjectBuilder injectBuilder;
@Before
public void setUp() throws Exception {
injectBuilder = new InjectBuilder(mock(ResponseBuilder.class));
}
@Test
public void shouldBuildAnInjectWithAFunction() throws Exception {
String injection = "some function"; | Inject expectedInject = new Inject().withFunction(injection); |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/fluent/ResponseTypeBuilderTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Response.java
// public abstract class Response extends HashMap {
//
// public JSONObject getJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return getJSON().toJSONString();
// }
// }
| import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.http.responses.Response;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock; | package org.mbtest.javabank.fluent;
public class ResponseTypeBuilderTest {
private ResponseBuilder parent;
private ResponseTypeBuilder responseTypeBuilder;
@Before
public void setUp() throws Exception {
parent = mock(ResponseBuilder.class);
responseTypeBuilder = new TestResponseBuilder(parent);
}
@Test
public void shouldEndWithItsParent() throws Exception {
assertThat(responseTypeBuilder.end(), is(parent));
}
private class TestResponseBuilder extends ResponseTypeBuilder {
TestResponseBuilder(ResponseBuilder parent) {
super(parent);
}
@Override | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Response.java
// public abstract class Response extends HashMap {
//
// public JSONObject getJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return getJSON().toJSONString();
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/fluent/ResponseTypeBuilderTest.java
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.http.responses.Response;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
package org.mbtest.javabank.fluent;
public class ResponseTypeBuilderTest {
private ResponseBuilder parent;
private ResponseTypeBuilder responseTypeBuilder;
@Before
public void setUp() throws Exception {
parent = mock(ResponseBuilder.class);
responseTypeBuilder = new TestResponseBuilder(parent);
}
@Test
public void shouldEndWithItsParent() throws Exception {
assertThat(responseTypeBuilder.end(), is(parent));
}
private class TestResponseBuilder extends ResponseTypeBuilder {
TestResponseBuilder(ResponseBuilder parent) {
super(parent);
}
@Override | protected Response build() { |
thejamesthomas/javabank | javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
| import org.mbtest.javabank.http.imposters.Imposter;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList; | package org.mbtest.javabank.fluent;
public class ImposterBuilder {
private int port;
private List<StubBuilder> stubBuilders = newArrayList();
public static ImposterBuilder anImposter() {
return new ImposterBuilder();
}
public ImposterBuilder onPort(int port) {
this.port = port;
return this;
}
public StubBuilder stub() {
StubBuilder child = new StubBuilder(this);
stubBuilders.add(child);
return child;
}
| // Path: javabank-core/src/main/java/org/mbtest/javabank/http/imposters/Imposter.java
// public class Imposter extends HashMap {
// private static final String PORT = "port";
// private static final String PROTOCOL = "protocol";
// private static final String STUBS = "stubs";
//
// public Imposter() {
// this.put(PROTOCOL, "http");
// this.put(STUBS, newArrayList());
// }
//
// public static Imposter fromJSON(JSONObject json) {
// Imposter imposter = new Imposter();
// imposter.putAll(json);
//
// return imposter;
// }
//
// public static Imposter anImposter() {
// return new Imposter();
// }
//
// public Imposter onPort(int port) {
// this.put(PORT, port);
// return this;
// }
//
// public Imposter addStub(Stub stub) {
// getStubs().add(stub);
// return this;
// }
//
// public Imposter withStub(Stub stub) {
// this.remove(STUBS);
// this.put(STUBS, newArrayList());
// addStub(stub);
// return this;
// }
//
// public List<Stub> getStubs() {
// return ((List) get(STUBS));
// }
//
// public Stub getStub(int index) {
// return getStubs().get(index);
// }
//
// public JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String toString() {
// return toJSON().toJSONString();
// }
//
// public int getPort() {
// return Integer.valueOf(String.valueOf(get(PORT)));
// }
// }
// Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
import org.mbtest.javabank.http.imposters.Imposter;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
package org.mbtest.javabank.fluent;
public class ImposterBuilder {
private int port;
private List<StubBuilder> stubBuilders = newArrayList();
public static ImposterBuilder anImposter() {
return new ImposterBuilder();
}
public ImposterBuilder onPort(int port) {
this.port = port;
return this;
}
public StubBuilder stub() {
StubBuilder child = new StubBuilder(this);
stubBuilders.add(child);
return child;
}
| public Imposter build() { |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/http/core/IsTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
| import com.google.common.collect.ImmutableMap;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat; | package org.mbtest.javabank.http.core;
public class IsTest {
private ImmutableMap<String, String> defaultHeaders;
@Before
public void setUp() throws Exception {
defaultHeaders = ImmutableMap.of(HttpHeaders.CONNECTION, "close");
}
@Test
public void shouldSetTheDefaultHttpStatusCodeTo200() { | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/http/core/IsTest.java
import com.google.common.collect.ImmutableMap;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat;
package org.mbtest.javabank.http.core;
public class IsTest {
private ImmutableMap<String, String> defaultHeaders;
@Before
public void setUp() throws Exception {
defaultHeaders = ImmutableMap.of(HttpHeaders.CONNECTION, "close");
}
@Test
public void shouldSetTheDefaultHttpStatusCodeTo200() { | Is is = new Is(); |
thejamesthomas/javabank | javabank-core/src/main/java/org/mbtest/javabank/fluent/PredicateTypeBuilder.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/Predicate.java
// public class Predicate extends HashMap {
// private static final String PATH = "path";
// private static final String METHOD = "method";
// private static final String QUERY = "query";
// private static final String HEADERS = "headers";
// private static final String REQUEST_FROM = "requestFrom";
// private static final String BODY = "body";
//
// private Map data;
// private PredicateType type;
//
// public Predicate(PredicateType type) {
// this.type = type;
// data = newHashMap();
// this.put(type.getValue(), data);
// }
//
// private Predicate addEntry(String key, String value) {
// data.put(key, value);
// return this;
// }
//
// private Predicate addEntry(String key, Map map) {
// data.put(key, map);
// return this;
// }
//
// private Predicate addMapEntry(String key, String name, String value) {
// if(!data.containsKey(key)) {
// data.put(key, newHashMap());
// }
//
// Map entryMap = (Map) data.get(key);
// entryMap.put(name, value);
//
// return this;
// }
//
// private Object getEntry(String key) {
// return this.data.get(key);
// }
//
// @Override
// public String toString() {
// return toJSON().toJSONString();
// }
//
// private JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String getType() {
// return type.getValue();
// }
//
// public Predicate withPath(String path) {
// addEntry(PATH, path);
// return this;
// }
//
// public Predicate withMethod(String method) {
// addEntry(METHOD, method);
// return this;
// }
//
// public Predicate withQueryParameters(Map<String, String> parameters) {
// addEntry(QUERY, parameters);
// return this;
// }
//
// public Predicate addQueryParameter(String name, String value) {
// addMapEntry(QUERY, name, value);
// return this;
// }
//
// public Predicate addHeader(String name, String value) {
// addMapEntry(HEADERS, name, value);
// return this;
// }
//
// public Predicate withRequestFrom(String host, String port) {
// addEntry(REQUEST_FROM, host + ":" + port);
// return this;
// }
//
// public Predicate withBody(String body) {
// addEntry(BODY, body);
// return this;
// }
//
// public String getPath() {
// return (String) getEntry(PATH);
// }
//
// public String getMethod() {
// return (String) getEntry(METHOD);
// }
//
// public String getRequestFrom() {
// return (String) getEntry(REQUEST_FROM);
// }
//
// public String getBody() {
// return (String) getEntry(BODY);
// }
//
// public Map<String, String> getQueryParameters() {
// return (Map<String, String>) getEntry(QUERY);
// }
//
// public String getQueryParameter(String parameter) {
// return getQueryParameters().get(parameter);
// }
//
// public Map<String, String> getHeaders() {
// return (Map<String, String>) getEntry(HEADERS);
// }
//
// public String getHeader(String name) {
// return getHeaders().get(name);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/PredicateType.java
// public enum PredicateType {
// EQUALS("equals"),
// DEEP_EQUALS("deepEquals"),
// CONTAINS("contains"),
// STARTS_WITH("startsWith"),
// ENDS_WITH("endsWith"),
// MATCHES("matches"),
// EXISTS("exists"),
// NOT("not"),
// OR("or"),
// AND("and"),
// INJECT("inject");
//
// @Getter
// private String value;
//
// PredicateType(String value) {
//
// this.value = value;
// }
// }
| import org.mbtest.javabank.http.predicates.Predicate;
import org.mbtest.javabank.http.predicates.PredicateType;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList; | package org.mbtest.javabank.fluent;
public class PredicateTypeBuilder implements FluentBuilder {
private StubBuilder parent;
private List<PredicateValueBuilder> childPredicateValueBuilders = newArrayList();
protected PredicateTypeBuilder(StubBuilder stubBuilder) {
this.parent = stubBuilder;
}
public PredicateValueBuilder equals() { | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/Predicate.java
// public class Predicate extends HashMap {
// private static final String PATH = "path";
// private static final String METHOD = "method";
// private static final String QUERY = "query";
// private static final String HEADERS = "headers";
// private static final String REQUEST_FROM = "requestFrom";
// private static final String BODY = "body";
//
// private Map data;
// private PredicateType type;
//
// public Predicate(PredicateType type) {
// this.type = type;
// data = newHashMap();
// this.put(type.getValue(), data);
// }
//
// private Predicate addEntry(String key, String value) {
// data.put(key, value);
// return this;
// }
//
// private Predicate addEntry(String key, Map map) {
// data.put(key, map);
// return this;
// }
//
// private Predicate addMapEntry(String key, String name, String value) {
// if(!data.containsKey(key)) {
// data.put(key, newHashMap());
// }
//
// Map entryMap = (Map) data.get(key);
// entryMap.put(name, value);
//
// return this;
// }
//
// private Object getEntry(String key) {
// return this.data.get(key);
// }
//
// @Override
// public String toString() {
// return toJSON().toJSONString();
// }
//
// private JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String getType() {
// return type.getValue();
// }
//
// public Predicate withPath(String path) {
// addEntry(PATH, path);
// return this;
// }
//
// public Predicate withMethod(String method) {
// addEntry(METHOD, method);
// return this;
// }
//
// public Predicate withQueryParameters(Map<String, String> parameters) {
// addEntry(QUERY, parameters);
// return this;
// }
//
// public Predicate addQueryParameter(String name, String value) {
// addMapEntry(QUERY, name, value);
// return this;
// }
//
// public Predicate addHeader(String name, String value) {
// addMapEntry(HEADERS, name, value);
// return this;
// }
//
// public Predicate withRequestFrom(String host, String port) {
// addEntry(REQUEST_FROM, host + ":" + port);
// return this;
// }
//
// public Predicate withBody(String body) {
// addEntry(BODY, body);
// return this;
// }
//
// public String getPath() {
// return (String) getEntry(PATH);
// }
//
// public String getMethod() {
// return (String) getEntry(METHOD);
// }
//
// public String getRequestFrom() {
// return (String) getEntry(REQUEST_FROM);
// }
//
// public String getBody() {
// return (String) getEntry(BODY);
// }
//
// public Map<String, String> getQueryParameters() {
// return (Map<String, String>) getEntry(QUERY);
// }
//
// public String getQueryParameter(String parameter) {
// return getQueryParameters().get(parameter);
// }
//
// public Map<String, String> getHeaders() {
// return (Map<String, String>) getEntry(HEADERS);
// }
//
// public String getHeader(String name) {
// return getHeaders().get(name);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/PredicateType.java
// public enum PredicateType {
// EQUALS("equals"),
// DEEP_EQUALS("deepEquals"),
// CONTAINS("contains"),
// STARTS_WITH("startsWith"),
// ENDS_WITH("endsWith"),
// MATCHES("matches"),
// EXISTS("exists"),
// NOT("not"),
// OR("or"),
// AND("and"),
// INJECT("inject");
//
// @Getter
// private String value;
//
// PredicateType(String value) {
//
// this.value = value;
// }
// }
// Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/PredicateTypeBuilder.java
import org.mbtest.javabank.http.predicates.Predicate;
import org.mbtest.javabank.http.predicates.PredicateType;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
package org.mbtest.javabank.fluent;
public class PredicateTypeBuilder implements FluentBuilder {
private StubBuilder parent;
private List<PredicateValueBuilder> childPredicateValueBuilders = newArrayList();
protected PredicateTypeBuilder(StubBuilder stubBuilder) {
this.parent = stubBuilder;
}
public PredicateValueBuilder equals() { | return getHttpMatcherBuilder(PredicateType.EQUALS); |
thejamesthomas/javabank | javabank-core/src/main/java/org/mbtest/javabank/fluent/PredicateTypeBuilder.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/Predicate.java
// public class Predicate extends HashMap {
// private static final String PATH = "path";
// private static final String METHOD = "method";
// private static final String QUERY = "query";
// private static final String HEADERS = "headers";
// private static final String REQUEST_FROM = "requestFrom";
// private static final String BODY = "body";
//
// private Map data;
// private PredicateType type;
//
// public Predicate(PredicateType type) {
// this.type = type;
// data = newHashMap();
// this.put(type.getValue(), data);
// }
//
// private Predicate addEntry(String key, String value) {
// data.put(key, value);
// return this;
// }
//
// private Predicate addEntry(String key, Map map) {
// data.put(key, map);
// return this;
// }
//
// private Predicate addMapEntry(String key, String name, String value) {
// if(!data.containsKey(key)) {
// data.put(key, newHashMap());
// }
//
// Map entryMap = (Map) data.get(key);
// entryMap.put(name, value);
//
// return this;
// }
//
// private Object getEntry(String key) {
// return this.data.get(key);
// }
//
// @Override
// public String toString() {
// return toJSON().toJSONString();
// }
//
// private JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String getType() {
// return type.getValue();
// }
//
// public Predicate withPath(String path) {
// addEntry(PATH, path);
// return this;
// }
//
// public Predicate withMethod(String method) {
// addEntry(METHOD, method);
// return this;
// }
//
// public Predicate withQueryParameters(Map<String, String> parameters) {
// addEntry(QUERY, parameters);
// return this;
// }
//
// public Predicate addQueryParameter(String name, String value) {
// addMapEntry(QUERY, name, value);
// return this;
// }
//
// public Predicate addHeader(String name, String value) {
// addMapEntry(HEADERS, name, value);
// return this;
// }
//
// public Predicate withRequestFrom(String host, String port) {
// addEntry(REQUEST_FROM, host + ":" + port);
// return this;
// }
//
// public Predicate withBody(String body) {
// addEntry(BODY, body);
// return this;
// }
//
// public String getPath() {
// return (String) getEntry(PATH);
// }
//
// public String getMethod() {
// return (String) getEntry(METHOD);
// }
//
// public String getRequestFrom() {
// return (String) getEntry(REQUEST_FROM);
// }
//
// public String getBody() {
// return (String) getEntry(BODY);
// }
//
// public Map<String, String> getQueryParameters() {
// return (Map<String, String>) getEntry(QUERY);
// }
//
// public String getQueryParameter(String parameter) {
// return getQueryParameters().get(parameter);
// }
//
// public Map<String, String> getHeaders() {
// return (Map<String, String>) getEntry(HEADERS);
// }
//
// public String getHeader(String name) {
// return getHeaders().get(name);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/PredicateType.java
// public enum PredicateType {
// EQUALS("equals"),
// DEEP_EQUALS("deepEquals"),
// CONTAINS("contains"),
// STARTS_WITH("startsWith"),
// ENDS_WITH("endsWith"),
// MATCHES("matches"),
// EXISTS("exists"),
// NOT("not"),
// OR("or"),
// AND("and"),
// INJECT("inject");
//
// @Getter
// private String value;
//
// PredicateType(String value) {
//
// this.value = value;
// }
// }
| import org.mbtest.javabank.http.predicates.Predicate;
import org.mbtest.javabank.http.predicates.PredicateType;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList; | return getHttpMatcherBuilder(PredicateType.EXISTS);
}
public PredicateValueBuilder not() {
return getHttpMatcherBuilder(PredicateType.NOT);
}
public PredicateValueBuilder or() {
return getHttpMatcherBuilder(PredicateType.OR);
}
public PredicateValueBuilder inject() {
return getHttpMatcherBuilder(PredicateType.INJECT);
}
public PredicateValueBuilder and() {
return getHttpMatcherBuilder(PredicateType.AND);
}
private PredicateValueBuilder getHttpMatcherBuilder(PredicateType type) {
PredicateValueBuilder predicateValueBuilder = new PredicateValueBuilder(this, type);
childPredicateValueBuilders.add(predicateValueBuilder);
return predicateValueBuilder;
}
@Override
public StubBuilder end() {
return parent;
}
| // Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/Predicate.java
// public class Predicate extends HashMap {
// private static final String PATH = "path";
// private static final String METHOD = "method";
// private static final String QUERY = "query";
// private static final String HEADERS = "headers";
// private static final String REQUEST_FROM = "requestFrom";
// private static final String BODY = "body";
//
// private Map data;
// private PredicateType type;
//
// public Predicate(PredicateType type) {
// this.type = type;
// data = newHashMap();
// this.put(type.getValue(), data);
// }
//
// private Predicate addEntry(String key, String value) {
// data.put(key, value);
// return this;
// }
//
// private Predicate addEntry(String key, Map map) {
// data.put(key, map);
// return this;
// }
//
// private Predicate addMapEntry(String key, String name, String value) {
// if(!data.containsKey(key)) {
// data.put(key, newHashMap());
// }
//
// Map entryMap = (Map) data.get(key);
// entryMap.put(name, value);
//
// return this;
// }
//
// private Object getEntry(String key) {
// return this.data.get(key);
// }
//
// @Override
// public String toString() {
// return toJSON().toJSONString();
// }
//
// private JSONObject toJSON() {
// return new JSONObject(this);
// }
//
// public String getType() {
// return type.getValue();
// }
//
// public Predicate withPath(String path) {
// addEntry(PATH, path);
// return this;
// }
//
// public Predicate withMethod(String method) {
// addEntry(METHOD, method);
// return this;
// }
//
// public Predicate withQueryParameters(Map<String, String> parameters) {
// addEntry(QUERY, parameters);
// return this;
// }
//
// public Predicate addQueryParameter(String name, String value) {
// addMapEntry(QUERY, name, value);
// return this;
// }
//
// public Predicate addHeader(String name, String value) {
// addMapEntry(HEADERS, name, value);
// return this;
// }
//
// public Predicate withRequestFrom(String host, String port) {
// addEntry(REQUEST_FROM, host + ":" + port);
// return this;
// }
//
// public Predicate withBody(String body) {
// addEntry(BODY, body);
// return this;
// }
//
// public String getPath() {
// return (String) getEntry(PATH);
// }
//
// public String getMethod() {
// return (String) getEntry(METHOD);
// }
//
// public String getRequestFrom() {
// return (String) getEntry(REQUEST_FROM);
// }
//
// public String getBody() {
// return (String) getEntry(BODY);
// }
//
// public Map<String, String> getQueryParameters() {
// return (Map<String, String>) getEntry(QUERY);
// }
//
// public String getQueryParameter(String parameter) {
// return getQueryParameters().get(parameter);
// }
//
// public Map<String, String> getHeaders() {
// return (Map<String, String>) getEntry(HEADERS);
// }
//
// public String getHeader(String name) {
// return getHeaders().get(name);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/predicates/PredicateType.java
// public enum PredicateType {
// EQUALS("equals"),
// DEEP_EQUALS("deepEquals"),
// CONTAINS("contains"),
// STARTS_WITH("startsWith"),
// ENDS_WITH("endsWith"),
// MATCHES("matches"),
// EXISTS("exists"),
// NOT("not"),
// OR("or"),
// AND("and"),
// INJECT("inject");
//
// @Getter
// private String value;
//
// PredicateType(String value) {
//
// this.value = value;
// }
// }
// Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/PredicateTypeBuilder.java
import org.mbtest.javabank.http.predicates.Predicate;
import org.mbtest.javabank.http.predicates.PredicateType;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
return getHttpMatcherBuilder(PredicateType.EXISTS);
}
public PredicateValueBuilder not() {
return getHttpMatcherBuilder(PredicateType.NOT);
}
public PredicateValueBuilder or() {
return getHttpMatcherBuilder(PredicateType.OR);
}
public PredicateValueBuilder inject() {
return getHttpMatcherBuilder(PredicateType.INJECT);
}
public PredicateValueBuilder and() {
return getHttpMatcherBuilder(PredicateType.AND);
}
private PredicateValueBuilder getHttpMatcherBuilder(PredicateType type) {
PredicateValueBuilder predicateValueBuilder = new PredicateValueBuilder(this, type);
childPredicateValueBuilders.add(predicateValueBuilder);
return predicateValueBuilder;
}
@Override
public StubBuilder end() {
return parent;
}
| protected List<Predicate> build() { |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
| import org.apache.http.HttpHeaders;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.core.Stub;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat; | package org.mbtest.javabank.http.imposters;
public class ImposterTest {
private String expectedProtocol = "http";
private int expectedPort;
@Before
public void setUp() throws Exception {
expectedPort = 4545;
}
@Test
public void shouldCreateAnImposter() {
Imposter imposter = Imposter.anImposter()
.onPort(expectedPort);
assertThat(imposter.getPort()).isEqualTo(expectedPort);
}
@Test
public void shouldCreateAnHttpImposterWithAStub() { | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java
import org.apache.http.HttpHeaders;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.core.Stub;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat;
package org.mbtest.javabank.http.imposters;
public class ImposterTest {
private String expectedProtocol = "http";
private int expectedPort;
@Before
public void setUp() throws Exception {
expectedPort = 4545;
}
@Test
public void shouldCreateAnImposter() {
Imposter imposter = Imposter.anImposter()
.onPort(expectedPort);
assertThat(imposter.getPort()).isEqualTo(expectedPort);
}
@Test
public void shouldCreateAnHttpImposterWithAStub() { | Stub expectedStub = new Stub(); |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
| import org.apache.http.HttpHeaders;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.core.Stub;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat; | .withStub(new Stub());
imposter.addStub(additionalStub);
assertThat(imposter.getStubs()).hasSize(2);
assertThat(imposter.getStubs()).contains(additionalStub);
}
@Test
public void shouldCreateAJsonObject() {
Imposter imposter = Imposter.anImposter()
.onPort(expectedPort)
.withStub(new Stub());
JSONObject expectedJson = new JSONObject();
expectedJson.put("port", expectedPort);
expectedJson.put("protocol", expectedProtocol);
JSONArray stubs = new JSONArray();
stubs.add(new Stub());
expectedJson.put("stubs", stubs);
assertThat(imposter.toJSON()).isEqualTo(expectedJson);
}
@Test
public void shouldCreateAJsonObjectWithBuilder() {
String expectedBody = "Hello World!";
int expectedStatusCode = 201;
String expectedContentType = "plain/text";
| // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java
import org.apache.http.HttpHeaders;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.core.Stub;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat;
.withStub(new Stub());
imposter.addStub(additionalStub);
assertThat(imposter.getStubs()).hasSize(2);
assertThat(imposter.getStubs()).contains(additionalStub);
}
@Test
public void shouldCreateAJsonObject() {
Imposter imposter = Imposter.anImposter()
.onPort(expectedPort)
.withStub(new Stub());
JSONObject expectedJson = new JSONObject();
expectedJson.put("port", expectedPort);
expectedJson.put("protocol", expectedProtocol);
JSONArray stubs = new JSONArray();
stubs.add(new Stub());
expectedJson.put("stubs", stubs);
assertThat(imposter.toJSON()).isEqualTo(expectedJson);
}
@Test
public void shouldCreateAJsonObjectWithBuilder() {
String expectedBody = "Hello World!";
int expectedStatusCode = 201;
String expectedContentType = "plain/text";
| Imposter imposter = ImposterBuilder.anImposter().onPort(expectedPort) |
thejamesthomas/javabank | javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
| import org.apache.http.HttpHeaders;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.core.Stub;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat; | .withStub(new Stub());
JSONObject expectedJson = new JSONObject();
expectedJson.put("port", expectedPort);
expectedJson.put("protocol", expectedProtocol);
JSONArray stubs = new JSONArray();
stubs.add(new Stub());
expectedJson.put("stubs", stubs);
assertThat(imposter.toJSON()).isEqualTo(expectedJson);
}
@Test
public void shouldCreateAJsonObjectWithBuilder() {
String expectedBody = "Hello World!";
int expectedStatusCode = 201;
String expectedContentType = "plain/text";
Imposter imposter = ImposterBuilder.anImposter().onPort(expectedPort)
.stub()
.response()
.is()
.body(expectedBody)
.statusCode(expectedStatusCode)
.header(com.google.common.net.HttpHeaders.CONTENT_TYPE, expectedContentType)
.end()
.end()
.end().build();
| // Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/ImposterBuilder.java
// public class ImposterBuilder {
// private int port;
// private List<StubBuilder> stubBuilders = newArrayList();
//
// public static ImposterBuilder anImposter() {
// return new ImposterBuilder();
// }
//
// public ImposterBuilder onPort(int port) {
// this.port = port;
// return this;
// }
//
// public StubBuilder stub() {
// StubBuilder child = new StubBuilder(this);
// stubBuilders.add(child);
// return child;
// }
//
// public Imposter build() {
// Imposter imposter = new Imposter().onPort(port);
// for (StubBuilder stubBuilder : stubBuilders) {
// imposter.addStub(stubBuilder.build());
// }
// return imposter;
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
//
// Path: javabank-core/src/main/java/org/mbtest/javabank/http/responses/Is.java
// public class Is extends Response {
// private static final String IS = "is";
// private static final String HEADERS = "headers";
// private static final String BODY = "body";
// private static final String STATUS_CODE = "statusCode";
// public static final String MODE = "_mode";
//
// private final Map<String, Object> data;
// private Map<String, String> headers;
//
// public Is() {
// headers = newHashMap();
// headers.put(HttpHeaders.CONNECTION, "close");
//
// this.data = newHashMap();
// this.data.put(STATUS_CODE, 200);
// this.data.put(HEADERS, headers);
//
// this.put(IS, data);
// withStatusCode(HttpStatus.SC_OK);
// withBody("");
// }
//
// public Is withStatusCode(int statusCode) {
// this.data.put("statusCode", statusCode);
// return this;
// }
//
// public Is withHeader(String name, String value) {
// this.headers.clear();
// addHeader(name, value);
// return this;
// }
//
// public Is addHeader(String name, String value) {
// this.headers.put(name, value);
// return this;
// }
//
// public Is withBody(String body) {
// this.data.put(BODY, body);
// return this;
// }
//
// public Is withMode(String mode){
// if(!Objects.isNull(mode)) {
// this.data.put(MODE, mode);
// }
// return this;
// }
//
// public Is withHeaders(Map<String, String> headers) {
// this.headers = headers;
// this.data.put(HEADERS, headers); // issue #5
// return this;
// }
//
// public int getStatusCode() {
// return Integer.valueOf(String.valueOf(this.data.get(STATUS_CODE)));
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public String getBody() {
// return (String) this.data.get(BODY);
// }
//
// public String getMode() {
// return (String) this.data.get(MODE);
// }
// }
// Path: javabank-core/src/test/java/org/mbtest/javabank/http/imposters/ImposterTest.java
import org.apache.http.HttpHeaders;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mbtest.javabank.fluent.ImposterBuilder;
import org.mbtest.javabank.http.core.Stub;
import org.mbtest.javabank.http.responses.Is;
import static org.assertj.core.api.Assertions.assertThat;
.withStub(new Stub());
JSONObject expectedJson = new JSONObject();
expectedJson.put("port", expectedPort);
expectedJson.put("protocol", expectedProtocol);
JSONArray stubs = new JSONArray();
stubs.add(new Stub());
expectedJson.put("stubs", stubs);
assertThat(imposter.toJSON()).isEqualTo(expectedJson);
}
@Test
public void shouldCreateAJsonObjectWithBuilder() {
String expectedBody = "Hello World!";
int expectedStatusCode = 201;
String expectedContentType = "plain/text";
Imposter imposter = ImposterBuilder.anImposter().onPort(expectedPort)
.stub()
.response()
.is()
.body(expectedBody)
.statusCode(expectedStatusCode)
.header(com.google.common.net.HttpHeaders.CONTENT_TYPE, expectedContentType)
.end()
.end()
.end().build();
| final Is response = new Is(); |
thejamesthomas/javabank | javabank-core/src/main/java/org/mbtest/javabank/fluent/StubBuilder.java | // Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
| import org.mbtest.javabank.http.core.Stub;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList; | package org.mbtest.javabank.fluent;
public class StubBuilder implements FluentBuilder {
private ImposterBuilder parent;
private List<ResponseBuilder> childResponses = newArrayList();
private List<PredicateTypeBuilder> childPredicates = newArrayList();
protected StubBuilder(ImposterBuilder httpImposterBuilder) {
this.parent = httpImposterBuilder;
}
public ResponseBuilder response() {
ResponseBuilder childResponse = new ResponseBuilder(this);
childResponses.add(childResponse);
return childResponse;
}
public PredicateTypeBuilder predicate() {
PredicateTypeBuilder childPredicate = new PredicateTypeBuilder(this);
childPredicates.add(childPredicate);
return childPredicate;
}
@Override
public ImposterBuilder end() {
return parent;
}
| // Path: javabank-core/src/main/java/org/mbtest/javabank/http/core/Stub.java
// public class Stub extends HashMap {
//
// private static final String RESPONSES = "responses";
// private static final String PREDICATES = "predicates";
//
// public Stub() {
// this.put(RESPONSES, newArrayList());
// this.put(PREDICATES, newArrayList());
// }
//
// public Stub withResponse(Is response) {
// getResponses().clear();
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addResponse(Response response) {
// getResponses().add(response);
//
// return this;
// }
//
// public Stub addPredicates(List<Predicate> predicates) {
// getPredicates().addAll(predicates);
// return this;
// }
//
// public List<Response> getResponses() {
// return (List<Response>) this.get(RESPONSES);
// }
//
// public List<Predicate> getPredicates() {
// return (List<Predicate>) this.get(PREDICATES);
// }
//
// public HashMap getResponse(int index) {
// return getResponses().get(index);
// }
//
// public Predicate getPredicate(int index) {
// return getPredicates().get(index);
// }
// }
// Path: javabank-core/src/main/java/org/mbtest/javabank/fluent/StubBuilder.java
import org.mbtest.javabank.http.core.Stub;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
package org.mbtest.javabank.fluent;
public class StubBuilder implements FluentBuilder {
private ImposterBuilder parent;
private List<ResponseBuilder> childResponses = newArrayList();
private List<PredicateTypeBuilder> childPredicates = newArrayList();
protected StubBuilder(ImposterBuilder httpImposterBuilder) {
this.parent = httpImposterBuilder;
}
public ResponseBuilder response() {
ResponseBuilder childResponse = new ResponseBuilder(this);
childResponses.add(childResponse);
return childResponse;
}
public PredicateTypeBuilder predicate() {
PredicateTypeBuilder childPredicate = new PredicateTypeBuilder(this);
childPredicates.add(childPredicate);
return childPredicate;
}
@Override
public ImposterBuilder end() {
return parent;
}
| protected Stub build() { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.