index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CancelBuildAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.ArrayUtils; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "cancelBuild", instantiationStrategy = "per-lookup" ) public class CancelBuildAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( CancelBuildAction.class ); private int projectId; private int projectGroupId; private List<String> selectedProjects; private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { getContinuum().getDistributedBuildManager().cancelBuild( projectId ); } else { BuildsManager buildsManager = getContinuum().getBuildsManager(); buildsManager.cancelBuild( projectId ); } AuditLog event = new AuditLog( "Project id=" + projectId, AuditLogConstants.CANCEL_BUILD ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } catch ( BuildManagerException e ) { throw new ContinuumException( "Error while canceling build", e ); } return SUCCESS; } public String cancelBuilds() throws ContinuumException { if ( getSelectedProjects() == null || getSelectedProjects().isEmpty() ) { return SUCCESS; } int[] projectsId = new int[getSelectedProjects().size()]; for ( String selectedProjectId : getSelectedProjects() ) { int projectId = Integer.parseInt( selectedProjectId ); projectsId = ArrayUtils.add( projectsId, projectId ); } if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { for ( int i = 0; i < projectsId.length; i++ ) { getContinuum().getDistributedBuildManager().cancelBuild( projectsId[i] ); AuditLog event = new AuditLog( "Project id=" + projectsId[i], AuditLogConstants.CANCEL_BUILD ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); } } else { BuildsManager parallelBuildsManager = getContinuum().getBuildsManager(); parallelBuildsManager.removeProjectsFromBuildQueue( projectsId ); try { // now we must check if the current build is one of this int index = ArrayUtils.indexOf( projectsId, getCurrentProjectIdBuilding() ); if ( index > 0 ) { int projId = projectsId[index]; getContinuum().getBuildsManager().cancelBuild( projId ); AuditLog event = new AuditLog( "Project id=" + projId, AuditLogConstants.CANCEL_BUILD ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); } } catch ( BuildManagerException e ) { logger.error( e.getMessage() ); throw new ContinuumException( e.getMessage(), e ); } } return SUCCESS; } public String cancelGroupBuild() throws ContinuumException { try { checkBuildProjectInGroupAuthorization( getContinuum().getProjectGroup( projectGroupId ).getName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { getContinuum().getDistributedBuildManager().cancelGroupBuild( projectGroupId ); AuditLog event = new AuditLog( "Project Group id=" + projectGroupId, AuditLogConstants.CANCEL_BUILD ); event.setCategory( AuditLogConstants.PROJECT_GROUP ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } else { BuildsManager buildsManager = getContinuum().getBuildsManager(); List<ProjectScmRoot> scmRoots = getContinuum().getProjectScmRootByProjectGroup( projectGroupId ); if ( scmRoots != null ) { for ( ProjectScmRoot scmRoot : scmRoots ) { try { buildsManager.removeProjectGroupFromPrepareBuildQueue( projectGroupId, scmRoot.getScmRootAddress() ); //taskQueueManager.removeFromPrepareBuildQueue( projectGroupId, scmRoot.getScmRootAddress() ); } catch ( BuildManagerException e ) { throw new ContinuumException( "Unable to cancel group build", e ); } } } Collection<Project> projects = getContinuum().getProjectsInGroup( projectGroupId ); List<String> projectIds = new ArrayList<String>(); for ( Project project : projects ) { projectIds.add( Integer.toString( project.getId() ) ); } setSelectedProjects( projectIds ); return cancelBuilds(); } } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public List<String> getSelectedProjects() { return selectedProjects; } public void setSelectedProjects( List<String> selectedProjects ) { this.selectedProjects = selectedProjects; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } /** * @return -1 if not project currently building * @throws ContinuumException */ protected int getCurrentProjectIdBuilding() throws ContinuumException, BuildManagerException { Map<String, BuildProjectTask> currentBuilds = getContinuum().getBuildsManager().getCurrentBuilds(); Set<String> keySet = currentBuilds.keySet(); for ( String key : keySet ) { BuildProjectTask task = currentBuilds.get( key ); if ( task != null ) { return task.getProjectId(); } } return -1; } }
5,500
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ReleasePerformAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.configuration.BuildAgentConfigurationException; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.release.config.ContinuumReleaseDescriptor; import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.continuum.release.utils.ReleaseHelper; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.continuum.web.action.AbstractReleaseAction; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.release.ContinuumReleaseManagerListener; import org.apache.maven.continuum.release.DefaultReleaseManagerListener; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.scm.provider.svn.repository.SvnScmProviderRepository; import org.apache.maven.shared.release.ReleaseResult; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Edwin Punzalan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releasePerform", instantiationStrategy = "per-lookup" ) public class ReleasePerformAction extends AbstractReleaseAction { private int projectId; private String releaseId; private String scmUrl; private String scmUsername; private String scmPassword; private String scmTag; private String scmTagBase; private String goals = "clean deploy"; private String arguments; private boolean useReleaseProfile = true; private ContinuumReleaseManagerListener listener; private ReleaseResult result; private String projectGroupName = ""; private List<Profile> profiles; private int profileId; @Requirement private ReleaseHelper releaseHelper; @Requirement private LocalRepositoryHelper localRepositoryHelper; private void init() throws Exception { if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager distributedReleaseManager = getContinuum().getDistributedReleaseManager(); getReleasePluginParameters( distributedReleaseManager.getReleasePluginParameters( projectId, "pom.xml" ) ); } else { Project project = getContinuum().getProject( projectId ); String workingDirectory = getContinuum().getWorkingDirectory( project.getId() ).getPath(); ArtifactRepository localRepo = localRepositoryHelper.getLocalRepository( project.getProjectGroup().getLocalRepository() ); getReleasePluginParameters( localRepo, workingDirectory, "pom.xml" ); } } public String inputFromScm() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } try { init(); } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releasePerform.input.error", args ) ); return RELEASE_ERROR; } populateFromProject(); releaseId = ""; profiles = this.getContinuum().getProfileService().getAllProfiles(); return SUCCESS; } public String input() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } try { init(); } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releasePerform.input.error", args ) ); return RELEASE_ERROR; } return SUCCESS; } /** * FIXME olamy is it really the good place to do that ? should be moved to continuum-release * TODO handle remoteTagging */ private void getReleasePluginParameters( ArtifactRepository localRepo, String workingDirectory, String pomFilename ) throws Exception { Map<String, Object> params = releaseHelper.extractPluginParameters( localRepo, workingDirectory, pomFilename ); if ( params.get( "use-release-profile" ) != null ) { useReleaseProfile = (Boolean) params.get( "use-release-profile" ); } if ( params.get( "perform-goals" ) != null ) { goals = (String) params.get( "perform-goals" ); } if ( params.get( "arguments" ) != null ) { arguments = (String) params.get( "arguments" ); } } public String execute() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } Project project = getContinuum().getProject( projectId ); LocalRepository repository = project.getProjectGroup().getLocalRepository(); String username = getPrincipal(); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); try { releaseManager.releasePerform( projectId, releaseId, goals, arguments, useReleaseProfile, repository, username ); } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releasePerform.release.error", args ) ); return RELEASE_ERROR; } } else { listener = new DefaultReleaseManagerListener(); listener.setUsername( username ); ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); //todo should be configurable File performDirectory = new File( getContinuum().getConfiguration().getWorkingDirectory(), "releases-" + System.currentTimeMillis() ); performDirectory.mkdirs(); releaseManager.perform( releaseId, performDirectory, goals, arguments, useReleaseProfile, listener, repository ); } AuditLog event = new AuditLog( "ReleaseId=" + releaseId, AuditLogConstants.PERFORM_RELEASE ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( username ); event.log(); return SUCCESS; } public String executeFromScm() throws Exception { if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { Project project = getContinuum().getProject( projectId ); LocalRepository repository = project.getProjectGroup().getLocalRepository(); DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); Profile profile = null; if ( profileId != -1 ) { profile = getContinuum().getProfileService().getProfile( profileId ); } Map<String, String> environments = getEnvironments( profile, releaseManager.getDefaultBuildagent( projectId ) ); try { releaseId = releaseManager.releasePerformFromScm( projectId, goals, arguments, useReleaseProfile, repository, scmUrl, scmUsername, scmPassword, scmTag, scmTagBase, environments, getPrincipal() ); } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "distributedBuild.releasePerform.release.error", args ) ); return RELEASE_ERROR; } return SUCCESS; } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setScmSourceUrl( scmUrl ); descriptor.setScmUsername( scmUsername ); descriptor.setScmPassword( scmPassword ); descriptor.setScmReleaseLabel( scmTag ); descriptor.setScmTagBase( scmTagBase ); if ( profileId != -1 ) { Profile profile = getContinuum().getProfileService().getProfile( profileId ); descriptor.setEnvironments( getEnvironments( profile, null ) ); } do { releaseId = String.valueOf( System.currentTimeMillis() ); } while ( releaseManager.getPreparedReleases().containsKey( releaseId ) ); releaseManager.getPreparedReleases().put( releaseId, descriptor ); return execute(); } } private void populateFromProject() throws Exception { Project project = getContinuum().getProjectWithAllDetails( projectId ); scmUrl = project.getScmUrl(); scmUsername = project.getScmUsername(); scmPassword = project.getScmPassword(); if ( scmUrl.startsWith( "scm:svn:" ) ) { scmTagBase = new SvnScmProviderRepository( scmUrl, scmUsername, scmPassword ).getTagBase(); } else { scmTagBase = ""; } releaseId = ""; } private void getReleasePluginParameters( Map context ) { useReleaseProfile = DistributedReleaseUtil.getUseReleaseProfile( context, useReleaseProfile ); if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getPerformGoals( context, goals ) ) ) { goals = DistributedReleaseUtil.getPerformGoals( context, goals ); } if ( StringUtils.isNotEmpty( DistributedReleaseUtil.getArguments( context, "" ) ) ) { arguments = DistributedReleaseUtil.getArguments( context, "" ); } } public String getReleaseId() { return releaseId; } public void setReleaseId( String releaseId ) { this.releaseId = releaseId; } public String getScmUrl() { return scmUrl; } public void setScmUrl( String scmUrl ) { this.scmUrl = scmUrl; } public String getScmUsername() { return scmUsername; } public void setScmUsername( String scmUsername ) { this.scmUsername = scmUsername; } public String getScmPassword() { return scmPassword; } public void setScmPassword( String scmPassword ) { this.scmPassword = scmPassword; } public String getScmTag() { return scmTag; } public void setScmTag( String scmTag ) { this.scmTag = scmTag; } public String getScmTagBase() { return scmTagBase; } public void setScmTagBase( String scmTagBase ) { this.scmTagBase = scmTagBase; } public String getGoals() { return goals; } public void setGoals( String goals ) { this.goals = goals; } public boolean isUseReleaseProfile() { return useReleaseProfile; } public void setUseReleaseProfile( boolean useReleaseProfile ) { this.useReleaseProfile = useReleaseProfile; } public ContinuumReleaseManagerListener getListener() { return listener; } public void setListener( ContinuumReleaseManagerListener listener ) { this.listener = listener; } public ReleaseResult getResult() { return result; } public void setResult( ReleaseResult result ) { this.result = result; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public List<Profile> getProfiles() { return profiles; } public void setProfiles( List<Profile> profiles ) { this.profiles = profiles; } public int getProfileId() { return profileId; } public void setProfileId( int profileId ) { this.profileId = profileId; } public String getArguments() { return arguments; } public void setArguments( String arguments ) { this.arguments = arguments; } }
5,501
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildDefinitionAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringEscapeUtils; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.builddefinition.BuildDefinitionService; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.builddefinition.BuildDefinitionUpdatePolicyConstants; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.ProfileException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.exception.ContinuumActionException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * BuildDefinitionAction: * * @author Jesse McConnell <jmcconnell@apache.org> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildDefinition", instantiationStrategy = "per-lookup" ) public class BuildDefinitionAction extends ContinuumConfirmAction { private int buildDefinitionId; private int projectId; private int projectGroupId; private int scheduleId; private boolean defaultBuildDefinition; private boolean confirmed = false; private String executor; private String goals; private String arguments; private String buildFile; private boolean buildFresh; private Map<Integer, String> schedules; private List<Profile> profiles; private boolean groupBuildDefinition = false; private boolean groupBuildView = false; private String projectGroupName = ""; private int profileId; private String description; private List<String> buildDefinitionTypes; private String buildDefinitionType; private boolean alwaysBuild; private int updatePolicy = BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_ALWAYS; private Map<Integer, String> buildDefinitionUpdatePolicies; @Requirement private BuildDefinitionService buildDefinitionService; @Override public void prepare() throws Exception { super.prepare(); if ( schedules == null ) { schedules = new HashMap<Integer, String>(); Collection<Schedule> allSchedules = getContinuum().getSchedules(); for ( Schedule schedule : allSchedules ) { schedules.put( schedule.getId(), schedule.getName() ); } } // todo: missing from continuum, investigate if ( profiles == null ) { profiles = this.getContinuum().getProfileService().getAllProfiles(); } buildDefinitionTypes = new ArrayList<String>(); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR ); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR ); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR ); buildDefinitionUpdatePolicies = new HashMap<Integer, String>(); String text = getText( "buildDefinition.updatePolicy.always" ); buildDefinitionUpdatePolicies.put( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_ALWAYS, text ); text = getText( "buildDefinition.updatePolicy.never" ); buildDefinitionUpdatePolicies.put( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_NEVER, text ); text = getText( "buildDefinition.updatePolicy.newPom" ); buildDefinitionUpdatePolicies.put( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_ONLY_FOR_NEW_POM, text ); } /** * if there is a build definition id set, then retrieve it..either way set us to up to work with build definition * * @return action result */ @Override public String input() throws ContinuumException, ContinuumStoreException, BuildDefinitionServiceException { try { if ( executor == null ) { if ( projectId != 0 ) { executor = getContinuum().getProject( projectId ).getExecutorId(); } else { List<Project> projects = getContinuum().getProjectGroupWithProjects( projectGroupId ).getProjects(); if ( projects.size() > 0 ) { Project project = projects.get( 0 ); executor = project.getExecutorId(); } } } if ( buildDefinitionId != 0 ) { if ( projectId != 0 ) { checkModifyProjectBuildDefinitionAuthorization( getProjectGroupName() ); } else { checkModifyGroupBuildDefinitionAuthorization( getProjectGroupName() ); } BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); goals = buildDefinition.getGoals(); arguments = buildDefinition.getArguments(); buildFile = buildDefinition.getBuildFile(); buildFresh = buildDefinition.isBuildFresh(); scheduleId = buildDefinition.getSchedule().getId(); defaultBuildDefinition = buildDefinition.isDefaultForProject(); Profile profile = buildDefinition.getProfile(); if ( profile != null ) { profileId = profile.getId(); } description = buildDefinition.getDescription(); buildDefinitionType = buildDefinition.getType(); alwaysBuild = buildDefinition.isAlwaysBuild(); updatePolicy = buildDefinition.getUpdatePolicy(); } else { String preDefinedBuildFile = ""; if ( projectId != 0 ) { checkAddProjectBuildDefinitionAuthorization( getProjectGroupName() ); BuildDefinition bd = getContinuum().getDefaultBuildDefinition( projectId ); if ( bd != null ) { preDefinedBuildFile = bd.getBuildFile(); } } else { checkAddGroupBuildDefinitionAuthorization( getProjectGroupName() ); List<BuildDefinition> bds = getContinuum().getBuildDefinitionsForProjectGroup( projectGroupId ); if ( bds != null && !bds.isEmpty() ) { preDefinedBuildFile = bds.get( 0 ).getBuildFile(); } } if ( StringUtils.isEmpty( preDefinedBuildFile ) ) { if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executor ) ) { buildFile = ( (BuildDefinition) buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate().getBuildDefinitions().get( 0 ) ).getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executor ) ) { buildFile = ( (BuildDefinition) buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate().getBuildDefinitions().get( 0 ) ).getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executor ) ) { buildFile = ( (BuildDefinition) buildDefinitionService.getDefaultAntBuildDefinitionTemplate().getBuildDefinitions().get( 0 ) ).getBuildFile(); buildDefinitionType = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; } else { buildDefinitionType = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; } } else { buildFile = preDefinedBuildFile; } } // if buildDefinitionType is null it will find with the executor if ( StringUtils.isEmpty( buildDefinitionType ) ) { if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executor ) ) { buildDefinitionType = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; } else { buildDefinitionType = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; } } } catch ( AuthorizationRequiredException authzE ) { return REQUIRES_AUTHORIZATION; } return SUCCESS; } public String saveBuildDefinition() throws ContinuumException, ProfileException { if ( projectId != 0 && !groupBuildDefinition ) { return saveToProject(); } else { return saveToGroup(); } } public String saveToProject() throws ContinuumException, ProfileException { AuditLog event = null; String resource = "Project id=" + projectId + ":" + goals + " " + arguments; try { if ( buildDefinitionId == 0 ) { checkAddProjectBuildDefinitionAuthorization( getProjectGroupName() ); getContinuum().addBuildDefinitionToProject( projectId, getBuildDefinitionFromInput() ); event = new AuditLog( resource, AuditLogConstants.ADD_GOAL ); } else { checkModifyProjectBuildDefinitionAuthorization( getProjectGroupName() ); getContinuum().updateBuildDefinitionForProject( projectId, getBuildDefinitionFromInput() ); event = new AuditLog( resource, AuditLogConstants.MODIFY_GOAL ); } } catch ( ContinuumActionException cae ) { addActionError( cae.getMessage() ); return INPUT; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } event.setCategory( AuditLogConstants.BUILD_DEFINITION ); event.setCurrentUser( getPrincipal() ); event.log(); if ( groupBuildView ) { return "success_group"; } return SUCCESS; } public String saveToGroup() throws ContinuumException, ProfileException { try { BuildDefinition newBuildDef = getBuildDefinitionFromInput(); if ( getContinuum().getBuildDefinitionsForProjectGroup( projectGroupId ).size() == 0 ) { newBuildDef.setDefaultForProject( true ); } if ( buildDefinitionId == 0 ) { checkAddGroupBuildDefinitionAuthorization( getProjectGroupName() ); getContinuum().addBuildDefinitionToProjectGroup( projectGroupId, newBuildDef ); } else { checkModifyGroupBuildDefinitionAuthorization( getProjectGroupName() ); getContinuum().updateBuildDefinitionForProjectGroup( projectGroupId, newBuildDef ); } } catch ( ContinuumActionException cae ) { addActionError( cae.getMessage() ); return INPUT; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } if ( projectId != 0 ) { String resource = "Project id=" + projectId + ":" + goals + " " + arguments; AuditLog event = null; if ( buildDefinitionId == 0 ) { event = new AuditLog( resource, AuditLogConstants.ADD_GOAL ); } else { event = new AuditLog( resource, AuditLogConstants.MODIFY_GOAL ); } event.setCategory( AuditLogConstants.BUILD_DEFINITION ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } else { String resource = "Project Group id=" + projectGroupId + ":" + goals + " " + arguments; AuditLog event = null; if ( buildDefinitionId == 0 ) { event = new AuditLog( resource, AuditLogConstants.ADD_GOAL ); } else { event = new AuditLog( resource, AuditLogConstants.MODIFY_GOAL ); } event.setCategory( AuditLogConstants.BUILD_DEFINITION ); event.setCurrentUser( getPrincipal() ); event.log(); return "success_group"; } } public String removeFromProject() throws ContinuumException { try { checkRemoveProjectBuildDefinitionAuthorization( getProjectGroupName() ); if ( confirmed ) { getContinuum().removeBuildDefinitionFromProject( projectId, buildDefinitionId ); String resource = "Project id=" + projectId + ":" + goals + " " + arguments; AuditLog event = new AuditLog( resource, AuditLogConstants.REMOVE_GOAL ); event.setCategory( AuditLogConstants.BUILD_DEFINITION ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } else { BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); this.description = buildDefinition.getDescription(); this.goals = buildDefinition.getGoals(); return CONFIRM; } } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } } public String removeFromProjectGroup() throws ContinuumException { try { checkRemoveGroupBuildDefinitionAuthorization( getProjectGroupName() ); if ( confirmed ) { getContinuum().removeBuildDefinitionFromProjectGroup( projectGroupId, buildDefinitionId ); String resource = "Project Group id=" + projectGroupId + ":" + goals + " " + arguments; AuditLog event = new AuditLog( resource, AuditLogConstants.REMOVE_GOAL ); event.setCategory( AuditLogConstants.BUILD_DEFINITION ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } else { BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); this.description = buildDefinition.getDescription(); this.goals = buildDefinition.getGoals(); return CONFIRM; } } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } } private BuildDefinition getBuildDefinitionFromInput() throws ContinuumActionException, ProfileException { Schedule schedule; try { schedule = getContinuum().getSchedule( scheduleId ); } catch ( ContinuumException e ) { addActionError( getText( "unable to get schedule" ) ); throw new ContinuumActionException( "unable to get schedule" ); } BuildDefinition buildDefinition = new BuildDefinition(); if ( buildDefinitionId != 0 ) { buildDefinition.setId( buildDefinitionId ); } buildDefinition.setGoals( goals ); buildDefinition.setArguments( arguments ); buildDefinition.setBuildFile( buildFile ); buildDefinition.setBuildFresh( buildFresh ); buildDefinition.setDefaultForProject( defaultBuildDefinition ); buildDefinition.setSchedule( schedule ); if ( profileId != -1 ) { Profile profile = getContinuum().getProfileService().getProfile( profileId ); if ( profile != null ) { buildDefinition.setProfile( profile ); } } buildDefinition.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( description ) ) ); buildDefinition.setType( buildDefinitionType ); buildDefinition.setAlwaysBuild( alwaysBuild ); buildDefinition.setUpdatePolicy( updatePolicy ); return buildDefinition; } public int getBuildDefinitionId() { return buildDefinitionId; } public void setBuildDefinitionId( final int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public int getProjectId() { return projectId; } public void setProjectId( final int projectId ) { this.projectId = projectId; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( final int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getScheduleId() { return scheduleId; } public void setScheduleId( final int scheduleId ) { this.scheduleId = scheduleId; } public boolean isDefaultBuildDefinition() { return defaultBuildDefinition; } public void setDefaultBuildDefinition( final boolean defaultBuildDefinition ) { this.defaultBuildDefinition = defaultBuildDefinition; } @Override public boolean isConfirmed() { return confirmed; } @Override public void setConfirmed( final boolean confirmed ) { this.confirmed = confirmed; } public String getExecutor() { return executor; } public void setExecutor( final String executor ) { this.executor = executor; } public String getGoals() { return goals; } public void setGoals( final String goals ) { this.goals = goals; } public String getArguments() { return arguments; } public void setArguments( final String arguments ) { this.arguments = arguments; } public String getBuildFile() { return buildFile; } public void setBuildFile( final String buildFile ) { this.buildFile = buildFile; } public boolean isBuildFresh() { return buildFresh; } public void setBuildFresh( final boolean buildFresh ) { this.buildFresh = buildFresh; } public Map<Integer, String> getSchedules() { return schedules; } public void setSchedules( final Map<Integer, String> schedules ) { this.schedules = schedules; } public List<Profile> getProfiles() { return profiles; } public void setProfiles( final List<Profile> profiles ) { this.profiles = profiles; } public boolean isGroupBuildDefinition() { return groupBuildDefinition; } public void setGroupBuildDefinition( final boolean groupBuildDefinition ) { this.groupBuildDefinition = groupBuildDefinition; } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } } return projectGroupName; } public int getProfileId() { return profileId; } public void setProfileId( final int profileId ) { this.profileId = profileId; } public String getDescription() { return description; } public void setDescription( final String description ) { this.description = description; } public String getBuildDefinitionType() { return buildDefinitionType; } public void setBuildDefinitionType( final String buildDefinitionType ) { this.buildDefinitionType = buildDefinitionType; } public List<String> getBuildDefinitionTypes() { return buildDefinitionTypes; } public boolean isAlwaysBuild() { return alwaysBuild; } public void setAlwaysBuild( final boolean alwaysBuild ) { this.alwaysBuild = alwaysBuild; } public boolean isGroupBuildView() { return groupBuildView; } public void setGroupBuildView( final boolean groupBuildView ) { this.groupBuildView = groupBuildView; } public int getUpdatePolicy() { return updatePolicy; } public void setUpdatePolicy( int updatePolicy ) { this.updatePolicy = updatePolicy; } public Map<Integer, String> getBuildDefinitionUpdatePolicies() { return buildDefinitionUpdatePolicies; } }
5,502
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildProjectAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.buildagent.NoBuildAgentException; import org.apache.continuum.buildagent.NoBuildAgentInGroupException; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.build.BuildException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildProject", instantiationStrategy = "per-lookup" ) public class BuildProjectAction extends ContinuumActionSupport { private int projectId; private int buildDefinitionId; private int projectGroupId; private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } BuildTrigger buildTrigger = new BuildTrigger( ContinuumProjectState.TRIGGER_FORCED, getPrincipal() ); try { if ( projectId > 0 ) { if ( buildDefinitionId > 0 ) { getContinuum().buildProjectWithBuildDefinition( projectId, buildDefinitionId, buildTrigger ); addActionMessage( getText( "build.project.success" ) ); } else { getContinuum().buildProject( projectId, buildTrigger.getTriggeredBy() ); addActionMessage( getText( "build.project.success" ) ); } } else { if ( buildDefinitionId > 0 ) { getContinuum().buildProjectGroupWithBuildDefinition( projectGroupId, buildDefinitionId, buildTrigger ); addActionMessage( getText( "build.projects.success" ) ); } else { //TODO: Check if this code is called, I don't think //If it is, it should used the projectId getContinuum().buildProjects( buildTrigger.getTriggeredBy() ); addActionMessage( getText( "build.projects.success" ) ); } } } catch ( BuildException be ) { addActionError( be.getLocalizedMessage() ); } catch ( NoBuildAgentException e ) { addActionError( getText( "projectGroup.build.error.noBuildAgent" ) ); } catch ( NoBuildAgentInGroupException e ) { addActionError( getText( "projectGroup.build.error.noBuildAgentInGroup" ) ); } AuditLog event = new AuditLog( AuditLogConstants.FORCE_BUILD ); event.setCurrentUser( getPrincipal() ); if ( projectId > 0 ) { event.setResource( "Project id=" + projectId ); event.setCategory( AuditLogConstants.PROJECT ); } else { event.setResource( "Project Group id=" + projectGroupId ); event.setCategory( AuditLogConstants.PROJECT_GROUP ); } event.log(); return SUCCESS; } public void setProjectId( int projectId ) { this.projectId = projectId; } public int getProjectId() { return projectId; } public void setBuildDefinitionId( int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public int getBuildDefinition() { return buildDefinitionId; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { ProjectGroup projectGroup = getContinuum().getProjectGroupByProjectId( projectId ); projectGroupName = projectGroup.getName(); projectGroupId = projectGroup.getId(); } } return projectGroupName; } }
5,503
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ReleaseCleanupAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.configuration.BuildAgentConfigurationException; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.release.ContinuumReleaseManagerListener; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import java.util.ArrayList; import java.util.List; /** * @author Edwin Punzalan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releaseCleanup", instantiationStrategy = "per-lookup" ) public class ReleaseCleanupAction extends ContinuumActionSupport { private int projectId; private String releaseId; private String projectGroupName = ""; public String execute() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); try { String goal = releaseManager.releaseCleanup( releaseId ); if ( StringUtils.isNotBlank( goal ) ) { return goal; } else { throw new Exception( "No listener to cleanup for id " + releaseId ); } } catch ( BuildAgentConfigurationException e ) { List<Object> args = new ArrayList<Object>(); args.add( e.getMessage() ); addActionError( getText( "releaseCleanup.error", args ) ); return RELEASE_ERROR; } } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); releaseManager.getReleaseResults().remove( releaseId ); ContinuumReleaseManagerListener listener = (ContinuumReleaseManagerListener) releaseManager.getListeners().remove( releaseId ); if ( listener != null ) { String goal = listener.getGoalName(); return goal + "Finished"; } else { throw new Exception( "No listener to cleanup for id " + releaseId ); } } } public String getReleaseId() { return releaseId; } public void setReleaseId( String releaseId ) { this.releaseId = releaseId; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public int getProjectGroupId() throws ContinuumException { return getContinuum().getProjectGroupByProjectId( projectId ).getId(); } }
5,504
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AddProjectAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.config.ConfigurationManager; import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.util.ValueStackFactory; import org.apache.commons.lang.StringEscapeUtils; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.ProfileException; import org.apache.maven.continuum.profile.ProfileService; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author Nick Gonzalez */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "addProject", instantiationStrategy = "per-lookup" ) public class AddProjectAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( AddProjectAction.class ); private String projectName; private String projectDescription; private String projectVersion; private String projectScmUrl; private String projectScmUsername; private String projectScmPassword; private String projectScmTag; private String projectType; private Collection<ProjectGroup> projectGroups; private int selectedProjectGroup; private String projectGroupName; private boolean disableGroupSelection; private boolean projectScmUseCache; private List<Profile> profiles; @Requirement( hint = "default" ) private ProfileService profileService; private int projectGroupId; private int buildDefintionTemplateId; private List<BuildDefinitionTemplate> buildDefinitionTemplates; private boolean emptyProjectGroups; public String add() throws ContinuumException, ProfileException, BuildDefinitionServiceException { initializeProjectGroupName(); initializeActionContext(); try { if ( StringUtils.isEmpty( getProjectGroupName() ) ) { checkAddProjectGroupAuthorization(); } else { checkAddProjectToGroupAuthorization( getProjectGroupName() ); } } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } if ( isEmptyProjectGroups() ) { addActionError( getText( "addProject.projectGroup.required" ) ); } String projectNameTrim = projectName.trim(); String versionTrim = projectVersion.trim(); String scmTrim = projectScmUrl.trim(); //TODO: Instead of get all projects then test them, it would be better to check it directly in the DB for ( Project project : getContinuum().getProjects() ) { // CONTINUUM-1445 if ( StringUtils.equalsIgnoreCase( project.getName(), projectNameTrim ) && StringUtils.equalsIgnoreCase( project.getVersion(), versionTrim ) && StringUtils.equalsIgnoreCase( project.getScmUrl(), scmTrim ) ) { addActionError( getText( "projectName.already.exist.error" ) ); break; } } if ( hasActionErrors() ) { return INPUT; } Project project = new Project(); project.setName( projectNameTrim ); if ( projectDescription != null ) { project.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( projectDescription.trim() ) ) ); } project.setVersion( versionTrim ); project.setScmUrl( scmTrim ); project.setScmUsername( projectScmUsername ); project.setScmPassword( projectScmPassword ); project.setScmTag( projectScmTag ); project.setScmUseCache( projectScmUseCache ); project.setExecutorId( projectType ); getContinuum().addProject( project, projectType, selectedProjectGroup, this.getBuildDefintionTemplateId() ); if ( this.getSelectedProjectGroup() > 0 ) { this.setProjectGroupId( this.getSelectedProjectGroup() ); return "projectGroupSummary"; } AuditLog event = new AuditLog( "Project id=" + project.getId(), AuditLogConstants.ADD_PROJECT ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } public String input() throws ContinuumException, ProfileException, BuildDefinitionServiceException { try { if ( StringUtils.isEmpty( getProjectGroupName() ) ) { checkAddProjectGroupAuthorization(); } else { checkAddProjectToGroupAuthorization( getProjectGroupName() ); } } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } projectGroups = new ArrayList<ProjectGroup>(); Collection<ProjectGroup> allProjectGroups = getContinuum().getAllProjectGroups(); for ( ProjectGroup pg : allProjectGroups ) { if ( isAuthorizedToAddProjectToGroup( pg.getName() ) ) { projectGroups.add( pg ); } } this.profiles = profileService.getAllProfiles(); buildDefinitionTemplates = getContinuum().getBuildDefinitionService().getAllBuildDefinitionTemplate(); return INPUT; } private void initializeProjectGroupName() { if ( disableGroupSelection ) { try { projectGroupName = getContinuum().getProjectGroup( selectedProjectGroup ).getName(); } catch ( ContinuumException e ) { e.printStackTrace(); } } } private void initializeActionContext() { // ctan: hack for WW-3161 if ( ActionContext.getContext() == null ) { // This fix allow initialization of ActionContext.getContext() to avoid NPE ConfigurationManager configurationManager = new ConfigurationManager(); configurationManager.addContainerProvider( new XWorkConfigurationProvider() ); com.opensymphony.xwork2.config.Configuration config = configurationManager.getConfiguration(); Container container = config.getContainer(); ValueStack stack = container.getInstance( ValueStackFactory.class ).createValueStack(); stack.getContext().put( ActionContext.CONTAINER, container ); ActionContext.setContext( new ActionContext( stack.getContext() ) ); } } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public String getProjectScmPassword() { return projectScmPassword; } public void setProjectScmPassword( String projectScmPassword ) { this.projectScmPassword = projectScmPassword; } public String getProjectScmTag() { return projectScmTag; } public void setProjectScmTag( String projectScmTag ) { this.projectScmTag = projectScmTag; } public String getProjectScmUrl() { return projectScmUrl; } public void setProjectScmUrl( String projectScmUrl ) { this.projectScmUrl = projectScmUrl; } public String getProjectScmUsername() { return projectScmUsername; } public void setProjectScmUsername( String projectScmUsername ) { this.projectScmUsername = projectScmUsername; } public String getProjectType() { return projectType; } public void setProjectType( String projectType ) { this.projectType = projectType; } public String getProjectVersion() { return projectVersion; } public void setProjectVersion( String projectVersion ) { this.projectVersion = projectVersion; } public Collection<ProjectGroup> getProjectGroups() { return projectGroups; } public void setProjectGroups( Collection<ProjectGroup> projectGroups ) { this.projectGroups = projectGroups; } public int getSelectedProjectGroup() { return selectedProjectGroup; } public void setSelectedProjectGroup( int selectedProjectGroup ) { this.selectedProjectGroup = selectedProjectGroup; } public boolean isDisableGroupSelection() { return disableGroupSelection; } public void setDisableGroupSelection( boolean disableGroupSelection ) { this.disableGroupSelection = disableGroupSelection; } public String getProjectGroupName() { return projectGroupName; } public void setProjectGroupName( String projectGroupName ) { this.projectGroupName = projectGroupName; } public boolean isProjectScmUseCache() { return projectScmUseCache; } public void setProjectScmUseCache( boolean projectScmUseCache ) { this.projectScmUseCache = projectScmUseCache; } public List<Profile> getProfiles() { return profiles; } public void setProfiles( List<Profile> profiles ) { this.profiles = profiles; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getBuildDefintionTemplateId() { return buildDefintionTemplateId; } public void setBuildDefintionTemplateId( int buildDefintionTemplateId ) { this.buildDefintionTemplateId = buildDefintionTemplateId; } public List<BuildDefinitionTemplate> getBuildDefinitionTemplates() { return buildDefinitionTemplates; } public void setBuildDefinitionTemplates( List<BuildDefinitionTemplate> buildDefinitionTemplates ) { this.buildDefinitionTemplates = buildDefinitionTemplates; } private boolean isAuthorizedToAddProjectToGroup( String projectGroupName ) { try { checkAddProjectToGroupAuthorization( projectGroupName ); return true; } catch ( AuthorizationRequiredException authzE ) { return false; } } public String getProjectDescription() { return projectDescription; } public void setProjectDescription( String projectDescription ) { this.projectDescription = projectDescription; } public boolean isEmptyProjectGroups() { return emptyProjectGroups; } public void setEmptyProjectGroups( boolean emptyProjectGroups ) { this.emptyProjectGroups = emptyProjectGroups; } }
5,505
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/SurefireReportAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.reports.surefire.ReportTest; import org.apache.maven.continuum.reports.surefire.ReportTestSuite; import org.apache.maven.continuum.reports.surefire.ReportTestSuiteGenerator; import org.apache.maven.continuum.reports.surefire.ReportTestSuiteGeneratorException; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @author Edwin Punzalan * @todo too many inner classes, maybe a continuum-reports project group ? */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "surefireReport", instantiationStrategy = "per-lookup" ) public class SurefireReportAction extends ContinuumActionSupport { @Requirement private ReportTestSuiteGenerator reportTestSuiteGenerator; private int buildId; private int projectId; private List<ReportTestSuite> testSuites; private List<ReportTest> testSummaryList; private List<ReportTest> testPackageList; private String projectName; private Project project; public String execute() throws ContinuumException, ConfigurationException, ReportTestSuiteGeneratorException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } project = getProjectById( projectId ); testSuites = reportTestSuiteGenerator.generateReports( buildId, projectId ); getSummary( testSuites ); getDetails( testSuites ); return SUCCESS; } private void getSummary( List<ReportTestSuite> suiteList ) { int totalTests = 0; int totalErrors = 0; int totalFailures = 0; float totalTime = 0.0f; for ( ReportTestSuite suite : suiteList ) { totalTests += suite.getNumberOfTests(); totalErrors += suite.getNumberOfErrors(); totalFailures += suite.getNumberOfFailures(); totalTime += suite.getTimeElapsed(); } ReportTest report = new ReportTest(); report.setTests( totalTests ); report.setErrors( totalErrors ); report.setFailures( totalFailures ); report.setElapsedTime( totalTime ); testSummaryList = Collections.singletonList( report ); } private void getDetails( List<ReportTestSuite> suiteList ) { Map<String, ReportTest> testsByPackage = new LinkedHashMap<String, ReportTest>(); for ( ReportTestSuite suite : suiteList ) { ReportTest report = testsByPackage.get( suite.getPackageName() ); if ( report == null ) { report = new ReportTest(); report.setId( suite.getPackageName() ); report.setName( suite.getPackageName() ); } report.setTests( report.getTests() + suite.getNumberOfTests() ); report.setErrors( report.getErrors() + suite.getNumberOfErrors() ); report.setFailures( report.getFailures() + suite.getNumberOfFailures() ); report.setElapsedTime( report.getElapsedTime() + suite.getTimeElapsed() ); ReportTest reportTest = new ReportTest(); reportTest.setId( suite.getPackageName() + "." + suite.getName() ); reportTest.setName( suite.getName() ); reportTest.setTests( suite.getNumberOfTests() ); reportTest.setErrors( suite.getNumberOfErrors() ); reportTest.setFailures( suite.getNumberOfFailures() ); reportTest.setElapsedTime( suite.getTimeElapsed() ); reportTest.setChildren( suite.getTestCases() ); report.getChildren().add( reportTest ); testsByPackage.put( suite.getPackageName(), report ); } testPackageList = new ArrayList<ReportTest>( testsByPackage.values() ); } public int getBuildId() { return buildId; } public void setBuildId( int buildId ) { this.buildId = buildId; } public Project getProject() { return project; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public List<ReportTestSuite> getTestSuites() { return testSuites; } public void setTestSuites( List<ReportTestSuite> testSuites ) { this.testSuites = testSuites; } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public List<ReportTest> getTestSummaryList() { return testSummaryList; } public void setTestSummaryList( List<ReportTest> testSummaryList ) { this.testSummaryList = testSummaryList; } public List<ReportTest> getTestPackageList() { return testPackageList; } public void setTestPackageList( List<ReportTest> testPackageList ) { this.testPackageList = testPackageList; } public Project getProjectById( int projectId ) throws ContinuumException { return getContinuum().getProject( projectId ); } public String getProjectGroupName() throws ContinuumException { return getProjectById( projectId ).getProjectGroup().getName(); } }
5,506
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/GroupSummaryAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.project.ProjectGroupSummary; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.model.GroupSummary; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "groupSummary", instantiationStrategy = "per-lookup" ) public class GroupSummaryAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( GroupSummaryAction.class ); private String infoMessage; private List<GroupSummary> groups; public String browse() throws ContinuumException { groups = new ArrayList<GroupSummary>(); //TODO: Merge this two requests to one Collection<ProjectGroup> projectGroups = getContinuum().getAllProjectGroups(); Map<Integer, ProjectGroupSummary> summaries = getContinuum().getProjectsSummaryByGroups(); for ( ProjectGroup projectGroup : projectGroups ) { if ( isAuthorized( projectGroup.getName() ) ) { if ( logger.isDebugEnabled() ) { logger.debug( "GroupSummaryAction: building group " + projectGroup.getName() ); } GroupSummary groupModel = new GroupSummary(); groupModel.setId( projectGroup.getId() ); groupModel.setGroupId( projectGroup.getGroupId() ); groupModel.setName( projectGroup.getName() ); groupModel.setDescription( projectGroup.getDescription() ); ProjectGroupSummary summary = summaries.get( projectGroup.getId() ); if ( summary != null ) { groupModel.setNumProjects( summary.getNumberOfProjects() ); groupModel.setNumErrors( summary.getNumberOfErrors() ); groupModel.setNumFailures( summary.getNumberOfFailures() ); groupModel.setNumSuccesses( summary.getNumberOfSuccesses() ); } //todo wire in the next scheduled build for the project group and a meaningful status message //groupModel.setNextScheduledBuild( "unknown" ); //groupModel.setStatusMessage( "none" ); if ( logger.isDebugEnabled() ) { logger.debug( "GroupSummaryAction: adding group to groups list " + groupModel.getName() ); } groups.add( groupModel ); } } return SUCCESS; } public List<GroupSummary> getGroups() { return groups; } public String getInfoMessage() { return infoMessage; } public void setInfoMessage( String infoMessage ) { this.infoMessage = infoMessage; } private boolean isAuthorized( String projectGroupName ) { try { checkViewProjectGroupAuthorization( projectGroupName ); return true; } catch ( AuthorizationRequiredException authzE ) { return false; } } }
5,507
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectGroupAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.continuum.buildagent.NoBuildAgentException; import org.apache.continuum.buildagent.NoBuildAgentInGroupException; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.build.BuildException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.web.bean.ProjectGroupUserBean; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.RBACManager; import org.codehaus.plexus.redback.rbac.RbacManagerException; import org.codehaus.plexus.redback.rbac.RbacObjectNotFoundException; import org.codehaus.plexus.redback.rbac.Role; import org.codehaus.plexus.redback.rbac.UserAssignment; import org.codehaus.plexus.redback.role.RoleManager; import org.codehaus.plexus.redback.role.RoleManagerException; import org.codehaus.plexus.redback.users.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * ProjectGroupAction: * * @author Jesse McConnell <jmcconnell@apache.org> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "projectGroup", instantiationStrategy = "per-lookup" ) public class ProjectGroupAction extends ContinuumConfirmAction { private static final Logger logger = LoggerFactory.getLogger( ProjectGroupAction.class ); private static final Map<String, String> FILTER_CRITERIA = new HashMap<String, String>(); static { FILTER_CRITERIA.put( "username", "Username contains" ); FILTER_CRITERIA.put( "fullName", "Name contains" ); FILTER_CRITERIA.put( "email", "Email contains" ); } @Requirement( hint = "cached" ) private RBACManager rbac; @Requirement( hint = "default" ) private RoleManager roleManager; @Requirement( hint = "parallel" ) private BuildsManager parallelBuildsManager; private int projectGroupId; private ProjectGroup projectGroup; private String name; private String description; private Map projects = new HashMap(); private Map<Integer, String> projectGroups = new HashMap<Integer, String>(); private boolean projectInCOQueue = false; private Collection<Project> projectList; private List<ProjectGroupUserBean> projectGroupUsers; private String filterProperty; private String filterKey; //Default order is by username private String sorterProperty = "username"; private boolean ascending = true; private Collection groupProjects; private int releaseProjectId; private Map<String, Integer> buildDefinitions; private int buildDefinitionId; private boolean fromSummaryPage = false; private String preferredExecutor = "maven2"; private String url; private int repositoryId; private List<LocalRepository> repositories; private boolean disabledRepositories = true; private List<ProjectScmRoot> projectScmRoots; public void prepare() throws Exception { super.prepare(); repositories = getContinuum().getRepositoryService().getAllLocalRepositories(); } public String browse() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( ContinuumException e ) { addActionError( getText( "projectGroup.invalid.id", "Invalid Project Group Id: " + projectGroupId, Integer.toString( projectGroupId ) ) ); return "to_summary_page"; } projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId ); List<BuildDefinition> projectGroupBuildDefs = getContinuum().getBuildDefinitionsForProjectGroup( projectGroupId ); if ( projectGroupBuildDefs != null ) { this.buildDefinitions = new LinkedHashMap<String, Integer>( projectGroupBuildDefs.size() ); for ( BuildDefinition buildDefinition : projectGroupBuildDefs ) { if ( !buildDefinition.isDefaultForProject() ) { String key = StringUtils.isEmpty( buildDefinition.getDescription() ) ? buildDefinition.getGoals() : buildDefinition.getDescription(); buildDefinitions.put( key, buildDefinition.getId() ); } } } else { this.buildDefinitions = Collections.EMPTY_MAP; } if ( projectGroup != null ) { if ( projectGroup.getProjects() != null && projectGroup.getProjects().size() > 0 ) { int nbMaven2Projects = 0; int nbMaven1Projects = 0; int nbAntProjects = 0; int nbShellProjects = 0; Project rootProject = ( getContinuum().getProjectsInBuildOrder( getContinuum().getProjectsInGroupWithDependencies( projectGroupId ) ) ).get( 0 ); if ( "maven2".equals( rootProject.getExecutorId() ) || "maven-1".equals( rootProject.getExecutorId() ) ) { url = rootProject.getUrl(); } for ( Project p : projectGroup.getProjects() ) { if ( "maven2".equals( p.getExecutorId() ) ) { nbMaven2Projects += 1; } else if ( "maven-1".equals( p.getExecutorId() ) ) { nbMaven1Projects += 1; } else if ( "ant".equals( p.getExecutorId() ) ) { nbAntProjects += 1; } else if ( "shell".equals( p.getExecutorId() ) ) { nbShellProjects += 1; } } int nbActualPreferredProject = nbMaven2Projects; if ( nbMaven1Projects > nbActualPreferredProject ) { preferredExecutor = "maven-1"; nbActualPreferredProject = nbMaven1Projects; } if ( nbAntProjects > nbActualPreferredProject ) { preferredExecutor = "ant"; nbActualPreferredProject = nbAntProjects; } if ( nbShellProjects > nbActualPreferredProject ) { preferredExecutor = "shell"; } } projectScmRoots = getContinuum().getProjectScmRootByProjectGroup( projectGroup.getId() ); } return SUCCESS; } public String members() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId ); groupProjects = projectGroup.getProjects(); populateProjectGroupUsers( projectGroup ); return SUCCESS; } public Collection getGroupProjects() throws ContinuumException { return groupProjects; } public String buildDefinitions() throws ContinuumException { return browse(); } public String notifiers() throws ContinuumException { return browse(); } public String remove() throws ContinuumException { try { checkRemoveProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } try { getContinuum().removeProjectGroup( projectGroupId ); } catch ( ContinuumException e ) { logger.error( "Error while removing project group with id " + projectGroupId, e ); addActionError( getText( "projectGroup.delete.error", new String[] { Integer.toString( projectGroupId ), e.getMessage() } ) ); } AuditLog event = new AuditLog( "Project Group id=" + projectGroupId, AuditLogConstants.REMOVE_PROJECT_GROUP ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } public String confirmRemove() throws ContinuumException { try { checkRemoveProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } name = getProjectGroupName(); return CONFIRM; } private void initialize() throws ContinuumException { try { checkManageLocalRepositoriesAuthorization(); disabledRepositories = false; } catch ( AuthorizationRequiredException authzE ) { // do nothing } projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId ); projectList = projectGroup.getProjects(); if ( projectList != null ) { for ( Project p : projectList ) { try { if ( parallelBuildsManager.isInAnyCheckoutQueue( p.getId() ) ) { projectInCOQueue = true; } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } projects.put( p, p.getProjectGroup().getId() ); } } for ( ProjectGroup pg : getContinuum().getAllProjectGroups() ) { if ( isAuthorized( projectGroup.getName() ) ) { projectGroups.put( pg.getId(), pg.getName() ); } } repositories = getContinuum().getRepositoryService().getAllLocalRepositories(); } public String edit() throws ContinuumException { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } initialize(); name = projectGroup.getName(); description = projectGroup.getDescription(); projectList = projectGroup.getProjects(); if ( projectGroup.getLocalRepository() != null ) { repositoryId = projectGroup.getLocalRepository().getId(); } else { repositoryId = -1; } Collection<Project> projList = getContinuum().getProjectsInGroupWithDependencies( projectGroup.getId() ); if ( projList != null && projList.size() > 0 ) { Project rootProject = ( getContinuum().getProjectsInBuildOrder( projList ) ).get( 0 ); if ( rootProject != null ) { setUrl( rootProject.getUrl() ); } } return SUCCESS; } public String save() throws Exception { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } for ( ProjectGroup projectGroup : getContinuum().getAllProjectGroups() ) { if ( name.equals( projectGroup.getName() ) && projectGroup.getId() != projectGroupId ) { addActionError( getText( "projectGroup.error.name.already.exists" ) ); } } if ( hasActionErrors() ) { initialize(); return INPUT; } projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId ); // need to administer roles since they are based off of this // todo convert everything like to work off of string keys if ( !name.equals( projectGroup.getName() ) ) { // CONTINUUM-1502 name = name.trim(); try { roleManager.updateRole( "project-administrator", projectGroup.getName(), name ); roleManager.updateRole( "project-developer", projectGroup.getName(), name ); roleManager.updateRole( "project-user", projectGroup.getName(), name ); projectGroup.setName( name ); } catch ( RoleManagerException e ) { throw new ContinuumException( "unable to rename the project group", e ); } } projectGroup.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( description ) ) ); // [CONTINUUM-2228]. In select field can't select empty values. if ( repositoryId > 0 ) { LocalRepository repository = getContinuum().getRepositoryService().getLocalRepository( repositoryId ); projectGroup.setLocalRepository( repository ); } getContinuum().updateProjectGroup( projectGroup ); Collection<Project> projectList = getContinuum().getProjectsInGroupWithDependencies( projectGroupId ); if ( projectList != null && projectList.size() > 0 ) { Project rootProject = ( getContinuum().getProjectsInBuildOrder( projectList ) ).get( 0 ); rootProject.setUrl( url ); getContinuum().updateProject( rootProject ); } Iterator keys = projects.keySet().iterator(); while ( keys.hasNext() ) { String key = (String) keys.next(); String[] id = (String[]) projects.get( key ); int projectId = Integer.parseInt( key ); Project project = null; Iterator i = projectGroup.getProjects().iterator(); while ( i.hasNext() ) { project = (Project) i.next(); if ( projectId == project.getId() ) { break; } } ProjectGroup newProjectGroup = getContinuum().getProjectGroupWithProjects( new Integer( id[0] ) ); if ( newProjectGroup.getId() != projectGroup.getId() && isAuthorized( newProjectGroup.getName() ) ) { logger.info( "Moving project " + project.getName() + " to project group " + newProjectGroup.getName() ); project.setProjectGroup( newProjectGroup ); // CONTINUUM-1512 int batchSize = 100; Collection<BuildResult> results; do { results = getContinuum().getBuildResultsForProject( project.getId(), 0, batchSize ); for ( BuildResult br : results ) { getContinuum().removeBuildResult( br.getId() ); } } while ( results != null && results.size() > 0 ); getContinuum().updateProject( project ); } } AuditLog event = new AuditLog( "Project Group id=" + projectGroupId, AuditLogConstants.MODIFY_PROJECT_GROUP ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } public String build() throws ContinuumException { try { checkBuildProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } BuildTrigger buildTrigger = new BuildTrigger( ContinuumProjectState.TRIGGER_FORCED, getPrincipal() ); try { if ( this.getBuildDefinitionId() == -1 ) { getContinuum().buildProjectGroup( projectGroupId, buildTrigger ); } else { getContinuum().buildProjectGroupWithBuildDefinition( projectGroupId, buildDefinitionId, buildTrigger ); } addActionMessage( getText( "build.projects.success" ) ); } catch ( BuildException be ) { addActionError( be.getLocalizedMessage() ); } catch ( NoBuildAgentException e ) { addActionError( getText( "projectGroup.build.error.noBuildAgent" ) ); } catch ( NoBuildAgentInGroupException e ) { addActionError( getText( "projectGroup.build.error.noBuildAgentInGroup" ) ); } AuditLog event = new AuditLog( "Project Group id=" + projectGroupId, AuditLogConstants.FORCE_BUILD ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); if ( this.isFromSummaryPage() ) { return "to_summary_page"; } else { return SUCCESS; } } public String release() throws ContinuumException { try { checkBuildProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } // get the parent of the group by finding the parent project // i.e., the project that doesn't have a parent, or it's parent is not in the group. Project parent = null; boolean allBuildsOk = true; boolean allMavenTwo = true; projectList = getContinuum().getProjectsInGroupWithDependencies( projectGroupId ); if ( projectList != null ) { for ( Project p : projectList ) { if ( p.getState() != ContinuumProjectState.OK ) { logger.info( "Attempt to release group '" + projectGroup.getName() + "' failed as project '" + p.getName() + "' is in state " + p.getState() ); allBuildsOk = false; } if ( ( p.getParent() == null ) || ( !isParentInProjectGroup( p.getParent(), projectList ) ) ) { if ( parent == null ) { parent = p; } else { logger.info( "Attempt to release group '" + projectGroup.getName() + "' failed as project '" + p.getName() + "' and project '" + parent.getName() + "' are both parents" ); // currently, we have no provisions for releasing 2 or more parents // at the same time, this will be implemented in the future addActionError( getText( "projectGroup.release.error.severalParentProjects" ) ); return INPUT; } } if ( !"maven2".equals( p.getExecutorId() ) ) { logger.info( "Attempt to release group '" + projectGroup.getName() + "' failed as project '" + p.getName() + "' is not a Maven project (executor '" + p.getExecutorId() + "')" ); allMavenTwo = false; } } } if ( parent == null ) { addActionError( getText( "projectGroup.release.error.emptyGroup" ) ); return INPUT; } releaseProjectId = parent.getId(); if ( allBuildsOk && allMavenTwo ) { return SUCCESS; } else { addActionError( getText( "projectGroup.release.error.projectNotInSuccess" ) ); return INPUT; } } private boolean isParentInProjectGroup( ProjectDependency parent, Collection<Project> projectsInGroup ) throws ContinuumException { boolean result = false; for ( Project project : projectsInGroup ) { if ( parent != null ) { if ( ( project.getArtifactId().equals( parent.getArtifactId() ) ) && ( project.getGroupId().equals( parent.getGroupId() ) ) && ( project.getVersion().equals( parent.getVersion() ) ) ) { result = true; } } } return result; } private void populateProjectGroupUsers( ProjectGroup group ) { List<User> users = new ArrayList<User>(); try { List<Role> roles = rbac.getAllRoles(); List<String> roleNames = new ArrayList<String>(); for ( Role r : roles ) { String projectGroupName = StringUtils.substringAfter( r.getName(), "-" ).trim(); if ( projectGroupName.equals( group.getName() ) ) { roleNames.add( r.getName() ); } } List<UserAssignment> userAssignments = rbac.getUserAssignmentsForRoles( roleNames ); for ( UserAssignment ua : userAssignments ) { User u = getUser( ua.getPrincipal() ); if ( u != null ) { users.add( u ); } } } catch ( Exception e ) { logger.error( "Can't get the users list", e ); } if ( StringUtils.isNotBlank( filterKey ) ) { users = findUsers( users, filterProperty, filterKey ); } if ( StringUtils.isNotBlank( sorterProperty ) ) { sortUsers( users, sorterProperty, ascending ); } projectGroupUsers = new ArrayList<ProjectGroupUserBean>(); if ( users == null ) { return; } for ( User user : users ) { ProjectGroupUserBean pgUser = new ProjectGroupUserBean(); pgUser.setUser( user ); pgUser.setProjectGroup( group ); try { Collection<Role> effectiveRoles = rbac.getEffectivelyAssignedRoles( user.getUsername() ); boolean isGroupUser = false; for ( Role role : effectiveRoles ) { String projectGroupName = StringUtils.substringAfter( role.getName(), "-" ).trim(); if ( projectGroupName.equals( projectGroup.getName() ) ) { pgUser.addRole( role ); isGroupUser = true; } } if ( isGroupUser ) { projectGroupUsers.add( pgUser ); } } catch ( RbacObjectNotFoundException e ) { pgUser.setRoles( Collections.EMPTY_LIST ); } catch ( RbacManagerException e ) { pgUser.setRoles( Collections.EMPTY_LIST ); } } } private List<User> findUsers( List<User> users, String searchProperty, String searchKey ) { List<User> userList = new ArrayList<User>(); for ( User user : users ) { if ( "username".equals( searchProperty ) ) { String username = user.getUsername(); if ( username != null ) { if ( username.toLowerCase().indexOf( searchKey.toLowerCase() ) >= 0 ) { userList.add( user ); } } } else if ( "fullName".equals( searchProperty ) ) { String fullname = user.getFullName(); if ( fullname != null ) { if ( fullname.toLowerCase().indexOf( searchKey.toLowerCase() ) >= 0 ) { userList.add( user ); } } } else if ( "email".equals( searchProperty ) ) { String email = user.getEmail(); if ( email != null ) { if ( email.toLowerCase().indexOf( searchKey.toLowerCase() ) >= 0 ) { userList.add( user ); } } } } return userList; } private void sortUsers( List<User> userList, final String sorterProperty, final boolean orderAscending ) { Collections.sort( userList, new Comparator<User>() { public int compare( User o1, User o2 ) { String value1, value2; if ( "fullName".equals( sorterProperty ) ) { value1 = o1.getFullName(); value2 = o2.getFullName(); } else if ( "email".equals( sorterProperty ) ) { value1 = o1.getEmail(); value2 = o2.getEmail(); } else { value1 = o1.getUsername(); value2 = o2.getUsername(); } if ( orderAscending ) { return ComparatorUtils.nullLowComparator( null ).compare( value1, value2 ); } return ComparatorUtils.nullLowComparator( null ).compare( value2, value1 ); } } ); } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public ProjectGroup getProjectGroup() { return projectGroup; } public void setProjectGroup( ProjectGroup projectGroup ) { this.projectGroup = projectGroup; } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public Map getProjects() { return projects; } public void setProjects( Map projects ) { this.projects = projects; } public Map<Integer, String> getProjectGroups() { return projectGroups; } public void setProjectGroups( Map<Integer, String> projectGroups ) { this.projectGroups = projectGroups; } public boolean isProjectInCOQueue() { return projectInCOQueue; } public void setProjectInCOQueue( boolean projectInQueue ) { this.projectInCOQueue = projectInQueue; } public Collection<Project> getProjectList() { return projectList; } public List<ProjectGroupUserBean> getProjectGroupUsers() { return projectGroupUsers; } public boolean isAscending() { return ascending; } public void setAscending( boolean ascending ) { this.ascending = ascending; } public String getFilterKey() { return filterKey; } public void setFilterKey( String filterKey ) { this.filterKey = filterKey; } public String getFilterProperty() { return filterProperty; } public void setFilterProperty( String filterProperty ) { this.filterProperty = filterProperty; } public Map<String, String> getCriteria() { return FILTER_CRITERIA; } public void setReleaseProjectId( int releaseProjectId ) { this.releaseProjectId = releaseProjectId; } public int getReleaseProjectId() { return this.releaseProjectId; } public ProjectGroup getProjectGroup( int projectGroupId ) throws ContinuumException { if ( projectGroup == null ) { projectGroup = getContinuum().getProjectGroup( projectGroupId ); } else { if ( projectGroup.getId() != projectGroupId ) { projectGroup = getContinuum().getProjectGroup( projectGroupId ); } } return projectGroup; } public String getProjectGroupName() throws ContinuumException { return getProjectGroup( projectGroupId ).getName(); } public Map<String, Integer> getBuildDefinitions() { return buildDefinitions; } public void setBuildDefinitions( Map<String, Integer> buildDefinitions ) { this.buildDefinitions = buildDefinitions; } public int getBuildDefinitionId() { return buildDefinitionId; } public void setBuildDefinitionId( int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public boolean isFromSummaryPage() { return fromSummaryPage; } public void setFromSummaryPage( boolean fromSummaryPage ) { this.fromSummaryPage = fromSummaryPage; } public String getPreferredExecutor() { return preferredExecutor; } public String getUrl() { return url; } public void setUrl( String url ) { this.url = url; } public int getRepositoryId() { return repositoryId; } public void setRepositoryId( int repositoryId ) { this.repositoryId = repositoryId; } public List<LocalRepository> getRepositories() { return repositories; } public void setRepositories( List<LocalRepository> repositories ) { this.repositories = repositories; } public boolean isDisabledRepositories() { return disabledRepositories; } public void setDisabledRepositories( boolean disabledRepositories ) { this.disabledRepositories = disabledRepositories; } public List<ProjectScmRoot> getProjectScmRoots() { return projectScmRoots; } public void setProjectScmRoots( List<ProjectScmRoot> projectScmRoots ) { this.projectScmRoots = projectScmRoots; } private boolean isAuthorized( String projectGroupName ) { try { checkAddProjectToGroupAuthorization( projectGroupName ); return true; } catch ( AuthorizationRequiredException authzE ) { return false; } } public String getSorterProperty() { return sorterProperty; } public void setSorterProperty( String sorterProperty ) { this.sorterProperty = sorterProperty; } // for testing public void setRbacManager( RBACManager rbac ) { this.rbac = rbac; } }
5,508
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildResultAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.io.IOUtils; import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.builder.utils.ContinuumBuildConstant; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.util.StateGenerator; import org.apache.struts2.ServletActionContext; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildResult", instantiationStrategy = "per-lookup" ) public class BuildResultAction extends AbstractBuildAction { private static Logger log = LoggerFactory.getLogger( BuildResultAction.class ); @Requirement private FileSystemManager fsManager; @Requirement private DistributedBuildManager distributedBuildManager; private Project project; private BuildResult buildResult; private int buildId; private List<ChangeSet> changeSet; private boolean hasSurefireResults; private String buildOutput; private String state; private String projectGroupName = ""; private int projectGroupId; public String execute() throws ContinuumException, IOException, BuildManagerException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } //todo get this working for other types of test case rendering other then just surefire // check if there are surefire results to display project = getContinuum().getProject( getProjectId() ); ConfigurationService configuration = getContinuum().getConfiguration(); buildResult = getContinuum().getBuildResult( getBuildId() ); boolean runningOnAgent = false; if ( configuration.isDistributedBuildEnabled() ) { try { int buildDefinitionId = buildResult.getBuildDefinition().getId(); runningOnAgent = buildResult.getState() == ContinuumProjectState.BUILDING && distributedBuildManager.getCurrentRun( getProjectId(), buildDefinitionId ).getBuildResultId() == getBuildId(); } catch ( ContinuumException e ) { log.debug( "running distributed build not found: {}", e.getMessage() ); } } // view build result of the current build from the distributed build agent if ( runningOnAgent ) { Map<String, Object> map = distributedBuildManager.getBuildResult( project.getId() ); if ( map == null ) { projectGroupId = project.getProjectGroup().getId(); return ERROR; } if ( map.size() > 0 ) { buildResult = ContinuumBuildConstant.getBuildResult( map, null ); buildOutput = ContinuumBuildConstant.getBuildOutput( map ); if ( ServletActionContext.getRequest() != null ) { state = StateGenerator.generate( buildResult.getState(), ServletActionContext.getRequest().getContextPath() ); } } changeSet = null; hasSurefireResults = false; this.setCanDelete( false ); } else { buildResult = getContinuum().getBuildResult( getBuildId() ); // directory contains files ? File[] testReports = null; try { File surefireReportsDirectory = configuration.getTestReportsDirectory( buildId, getProjectId() ); testReports = surefireReportsDirectory.listFiles(); } catch ( ConfigurationException ce ) { log.warn( "failed to access test reports", ce ); } hasSurefireResults = testReports != null && testReports.length > 0; changeSet = getContinuum().getChangesSinceLastSuccess( getProjectId(), getBuildId() ); try { buildOutput = getBuildOutputText(); } catch ( ConfigurationException ce ) { log.warn( "failed to access build output", ce ); } if ( ServletActionContext.getRequest() != null ) { state = StateGenerator.generate( buildResult.getState(), ServletActionContext.getRequest().getContextPath() ); } this.setCanDelete( this.canRemoveBuildResult( buildResult ) ); } return SUCCESS; } public String remove() throws ContinuumException { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( this.isConfirmed() ) { try { if ( canRemoveBuildResult( getContinuum().getBuildResult( buildId ) ) ) { getContinuum().removeBuildResult( buildId ); } else { addActionError( getText( "buildResult.cannot.delete" ) ); } } catch ( ContinuumException e ) { addActionError( getText( "buildResult.delete.error", "Unable to delete build result", new Integer( buildId ).toString() ) ); } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } AuditLog event = new AuditLog( "Build Result id=" + buildId, AuditLogConstants.REMOVE_BUILD_RESULT ); event.setCategory( AuditLogConstants.BUILD_RESULT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } return CONFIRM; } public String buildLogAsText() throws ConfigurationException, IOException { buildOutput = getBuildOutputText(); return SUCCESS; } public InputStream getBuildOutputInputStream() throws ConfigurationException, IOException { return IOUtils.toInputStream( buildOutput ); } private String getBuildOutputText() throws ConfigurationException, IOException { ConfigurationService configuration = getContinuum().getConfiguration(); File buildOutputFile = configuration.getBuildOutputFile( getBuildId(), getProjectId() ); if ( buildOutputFile.exists() ) { return fsManager.fileContents( buildOutputFile ); } return null; } public int getBuildId() { return buildId; } public void setBuildId( int buildId ) { this.buildId = buildId; } public Project getProject() { return project; } public BuildResult getBuildResult() { return buildResult; } public List<ChangeSet> getChangesSinceLastSuccess() { return changeSet; } public boolean isHasSurefireResults() { return hasSurefireResults; } public void setHasSurefireResults( boolean hasSurefireResults ) { this.hasSurefireResults = hasSurefireResults; } public String getBuildOutput() { return buildOutput; } public String getState() { return state; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( getProjectId() ).getName(); } return projectGroupName; } public int getProjectGroupId() { return projectGroupId; } // for testing public void setDistributedBuildManager( DistributedBuildManager distributedBuildManager ) { this.distributedBuildManager = distributedBuildManager; } public boolean isBuildInProgress() { int buildState = buildResult.getState(); return buildState == ContinuumProjectState.BUILDING; } public boolean isBuildSuccessful() { return buildResult.getState() == ContinuumProjectState.OK; } public boolean isShowBuildNumber() { return buildResult.getBuildNumber() != 0; } public boolean isShowBuildError() { return !isBuildSuccessful() && !StringUtils.isEmpty( buildResult.getError() ); } }
5,509
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AddMavenProjectAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.config.ConfigurationManager; import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.util.ValueStackFactory; import org.apache.commons.lang.StringUtils; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.struts2.interceptor.ServletRequestAware; import org.codehaus.plexus.component.annotations.Requirement; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Action to add a Maven project to Continuum, either Maven 1 or Maven 2. * * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a> */ public abstract class AddMavenProjectAction extends ContinuumActionSupport implements ServletRequestAware { private static final long serialVersionUID = -3965565189557706469L; private static final int DEFINED_BY_POM_GROUP_ID = -1; @Requirement private FileSystemManager fsManager; private PomMethod pomMethod = PomMethod.HTTP; private String pomUrl; private File pomFile; private String pom = null; private String scmUsername; private String scmPassword; private Collection<ProjectGroup> projectGroups; private String projectGroupName; private int selectedProjectGroup = DEFINED_BY_POM_GROUP_ID; private boolean disableGroupSelection; private boolean scmUseCache; private int projectGroupId; private List<BuildDefinitionTemplate> buildDefinitionTemplates; private int buildDefinitionTemplateId; private List<String> errorMessages = new ArrayList<String>(); private HttpServletRequest httpServletRequest; public enum PomMethod { HTTP( "add.maven.project.pomMethod.http" ), FILE( "add.maven.project.pomMethod.file" ); private String textKey; PomMethod( String textKey ) { this.textKey = textKey; } public String getTextKey() { return textKey; } } /** * Generates locale-sensitive pom method options. */ public Map<PomMethod, String> getPomMethodOptions() { Map<PomMethod, String> options = new LinkedHashMap<PomMethod, String>(); for ( PomMethod type : PomMethod.values() ) { options.put( type, getText( type.getTextKey() ) ); } return options; } public void setPomMethod( PomMethod pomMethod ) { this.pomMethod = pomMethod; } public PomMethod getPomMethod() { return pomMethod; } public String execute() throws ContinuumException, BuildDefinitionServiceException { try { initializeProjectGroupName(); if ( StringUtils.isEmpty( getProjectGroupName() ) ) { checkAddProjectGroupAuthorization(); } else { checkAddProjectToGroupAuthorization( getProjectGroupName() ); } } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } // ctan: hack for WW-3161 if ( ActionContext.getContext() == null ) { // This fix allow initialization of ActionContext.getContext() to avoid NPE ConfigurationManager configurationManager = new ConfigurationManager(); configurationManager.addContainerProvider( new XWorkConfigurationProvider() ); com.opensymphony.xwork2.config.Configuration config = configurationManager.getConfiguration(); Container container = config.getContainer(); ValueStack stack = container.getInstance( ValueStackFactory.class ).createValueStack(); stack.getContext().put( ActionContext.CONTAINER, container ); ActionContext.setContext( new ActionContext( stack.getContext() ) ); } if ( pomMethod == PomMethod.HTTP && StringUtils.isNotEmpty( pomUrl ) ) { try { URL url = new URL( pomUrl ); if ( pomUrl.startsWith( "http" ) && !StringUtils.isEmpty( scmUsername ) ) { String encoding = this.httpServletRequest.getCharacterEncoding(); if ( StringUtils.isEmpty( encoding ) ) { encoding = System.getProperty( "file.encoding" ); } // URL encode username and password so things like @ or : or / don't corrupt URL String encodedUsername = URLEncoder.encode( scmUsername, encoding ); String encodedPassword = URLEncoder.encode( scmPassword, encoding ); StringBuffer urlBuffer = new StringBuffer(); urlBuffer.append( url.getProtocol() ).append( "://" ); urlBuffer.append( encodedUsername ).append( ':' ).append( encodedPassword ).append( '@' ).append( url.getHost() ); if ( url.getPort() != -1 ) { urlBuffer.append( ":" ).append( url.getPort() ); } urlBuffer.append( url.getPath() ); if ( url.getQuery() != null ) { urlBuffer.append( "?" + url.getQuery() ); } pom = urlBuffer.toString(); } else { pom = pomUrl; } } catch ( MalformedURLException e ) { addActionError( getText( "add.project.unknown.error" ) ); return doDefault(); } catch ( UnsupportedEncodingException e ) { addActionError( getText( "add.project.unknown.error" ) ); return doDefault(); } } else if ( pomMethod == PomMethod.FILE && pomFile != null ) { try { // CONTINUUM-1897 // File.c copyFile to tmp one File tmpPom = File.createTempFile( "continuum_tmp", "tmp" ); fsManager.copyFile( pomFile, tmpPom ); pom = tmpPom.toURL().toString(); } catch ( MalformedURLException e ) { // if local file can't be converted to url it's an internal error throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } } else { // no url or file was filled addActionError( getText( "add.project.field.required.error" ) ); return doDefault(); } boolean checkProtocol = pomMethod == PomMethod.HTTP; ContinuumProjectBuildingResult result = doExecute( pom, selectedProjectGroup, checkProtocol, scmUseCache ); if ( result.hasErrors() ) { for ( String key : result.getErrors() ) { String cause = result.getErrorsWithCause().get( key ); String msg = getText( key, new String[] { cause } ); // olamy : weird getText(key, String[]) must do that something like bla bla {0} // here an ugly hack for CONTINUUM-1675 if ( key.equals( ContinuumProjectBuildingResult.ERROR_MISSING_SCM ) ) { msg = getResourceBundle().getString( key ) + " " + cause; } if ( !StringUtils.equals( msg, key ) ) { errorMessages.add( msg ); } else { addActionError( msg ); } } return doDefault(); } if ( this.getSelectedProjectGroup() > 0 ) { this.setProjectGroupId( this.getSelectedProjectGroup() ); return "projectGroupSummary"; } if ( result.getProjectGroups() != null && !result.getProjectGroups(). isEmpty() ) { this.setProjectGroupId( ( result.getProjectGroups().get( 0 ) ).getId() ); return "projectGroupSummary"; } return SUCCESS; } /** * Subclasses must implement this method calling the appropiate operation on the continuum service. * * @param pomUrl url of the pom specified by the user * @param selectedProjectGroup project group id selected by the user * @param checkProtocol check if the protocol is allowed, use false if the pom is uploaded * @return result of adding the pom to continuum */ protected abstract ContinuumProjectBuildingResult doExecute( String pomUrl, int selectedProjectGroup, boolean checkProtocol, boolean scmUseCache ) throws ContinuumException; // TODO: Remove this method because a default method return SUCCESS instead of INPUT public String doDefault() throws BuildDefinitionServiceException { return input(); } public String input() throws BuildDefinitionServiceException { try { initializeProjectGroupName(); if ( StringUtils.isEmpty( getProjectGroupName() ) ) { checkAddProjectGroupAuthorization(); } else { checkAddProjectToGroupAuthorization( getProjectGroupName() ); } } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } Collection<ProjectGroup> allProjectGroups = getContinuum().getAllProjectGroups(); projectGroups = new ArrayList<ProjectGroup>(); ProjectGroup defaultGroup = new ProjectGroup(); defaultGroup.setId( DEFINED_BY_POM_GROUP_ID ); defaultGroup.setName( "Defined by POM" ); projectGroups.add( defaultGroup ); for ( ProjectGroup pg : allProjectGroups ) { if ( isAuthorizedToAddProjectToGroup( pg.getName() ) ) { projectGroups.add( pg ); } } initializeProjectGroupName(); this.setBuildDefinitionTemplates( getContinuum().getBuildDefinitionService().getAllBuildDefinitionTemplate() ); return INPUT; } protected String hidePasswordInUrl( String url ) { int indexAt = url.indexOf( "@" ); if ( indexAt < 0 ) { return url; } String s = url.substring( 0, indexAt ); int pos = s.lastIndexOf( ":" ); return s.substring( 0, pos + 1 ) + "*****" + url.substring( indexAt ); } private void initializeProjectGroupName() { if ( disableGroupSelection && selectedProjectGroup != DEFINED_BY_POM_GROUP_ID ) { try { projectGroupName = getContinuum().getProjectGroup( selectedProjectGroup ).getName(); } catch ( ContinuumException e ) { e.printStackTrace(); } } } public String getPom() { return pom; } public void setPom( String pom ) { this.pom = pom; } public File getPomFile() { return pomFile; } public void setPomFile( File pomFile ) { this.pomFile = pomFile; } public String getPomUrl() { return pomUrl; } public void setPomUrl( String pomUrl ) { this.pomUrl = pomUrl; } public void setScmPassword( String scmPassword ) { this.scmPassword = scmPassword; } public String getScmUsername() { return scmUsername; } public void setScmUsername( String scmUsername ) { this.scmUsername = scmUsername; } public Collection getProjectGroups() { return projectGroups; } public String getProjectGroupName() { return projectGroupName; } public void setProjectGroupName( String projectGroupName ) { this.projectGroupName = projectGroupName; } public int getSelectedProjectGroup() { return selectedProjectGroup; } public void setSelectedProjectGroup( int selectedProjectGroup ) { this.selectedProjectGroup = selectedProjectGroup; } public boolean isDisableGroupSelection() { return this.disableGroupSelection; } public void setDisableGroupSelection( boolean disableGroupSelection ) { this.disableGroupSelection = disableGroupSelection; } public boolean isScmUseCache() { return scmUseCache; } public void setScmUseCache( boolean scmUseCache ) { this.scmUseCache = scmUseCache; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public List<BuildDefinitionTemplate> getBuildDefinitionTemplates() { return buildDefinitionTemplates; } public void setBuildDefinitionTemplates( List<BuildDefinitionTemplate> buildDefinitionTemplates ) { this.buildDefinitionTemplates = buildDefinitionTemplates; } public int getBuildDefinitionTemplateId() { return buildDefinitionTemplateId; } public void setBuildDefinitionTemplateId( int buildDefinitionTemplateId ) { this.buildDefinitionTemplateId = buildDefinitionTemplateId; } private boolean isAuthorizedToAddProjectToGroup( String projectGroupName ) { try { checkAddProjectToGroupAuthorization( projectGroupName ); return true; } catch ( AuthorizationRequiredException authzE ) { return false; } } public List<String> getErrorMessages() { return errorMessages; } public void setErrorMessages( List<String> errorMessages ) { this.errorMessages = errorMessages; } public void setServletRequest( HttpServletRequest httpServletRequest ) { this.httpServletRequest = httpServletRequest; } }
5,510
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ReleaseProjectAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Edwin Punzalan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releaseProject", instantiationStrategy = "per-lookup" ) public class ReleaseProjectAction extends ContinuumActionSupport { private int projectId; private String projectName; private Map<String, String> preparedReleases; private String preparedReleaseId; private String goal; private String scmUrl; private Project project; private List releaseList; private String projectGroupName = ""; protected static final String REQUIRES_CONFIGURATION = "releaseOutputDir-required"; public String promptReleaseGoal() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } // check if releaseOutputDirectory is already set if ( getContinuum().getConfiguration().getReleaseOutputDirectory() == null ) { return REQUIRES_CONFIGURATION; } project = getContinuum().getProjectWithAllDetails( projectId ); if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); preparedReleases = releaseManager.getPreparedReleases( project.getGroupId(), project.getArtifactId() ); } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); this.preparedReleases = releaseManager.getPreparedReleasesForProject( project.getGroupId(), project.getArtifactId() ); } if ( !preparedReleases.isEmpty() ) { // use last release as default choice preparedReleaseId = new ArrayList<String>( preparedReleases.keySet() ).get( preparedReleases.size() - 1 ); } else { preparedReleaseId = null; } projectName = project.getName(); return SUCCESS; } public String execute() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( "prepare".equals( goal ) ) { return "prepareRelease"; } else if ( "perform".equals( goal ) ) { if ( "".equals( preparedReleaseId ) ) { return "performReleaseFromScm"; } else { return "performRelease"; } } else { return "prompt"; } } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getGoal() { return goal; } public void setGoal( String goal ) { this.goal = goal; } public Project getProject() { return project; } public void setProject( Project project ) { this.project = project; } public String getScmUrl() { return scmUrl; } public void setScmUrl( String scmUrl ) { this.scmUrl = scmUrl; } public List getReleaseList() { return releaseList; } public void setReleaseList( List releaseList ) { this.releaseList = releaseList; } public String getPreparedReleaseId() { return preparedReleaseId; } public void setPreparedReleaseId( String preparedReleaseId ) { this.preparedReleaseId = preparedReleaseId; } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public Map<String, String> getPreparedReleases() { return preparedReleases; } public void setPreparedReleases( Map<String, String> preparedReleases ) { this.preparedReleases = preparedReleases; } }
5,511
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ReleaseRollbackAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.configuration.BuildAgentConfigurationException; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.release.ContinuumReleaseException; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.release.ContinuumReleaseManagerListener; import org.apache.maven.continuum.release.DefaultReleaseManagerListener; import org.apache.maven.continuum.utils.WorkingDirectoryService; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; /** * @author Edwin Punzalan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releaseRollback", instantiationStrategy = "per-lookup" ) public class ReleaseRollbackAction extends ContinuumActionSupport { @Requirement private WorkingDirectoryService workingDirectoryService; private int projectId; private String releaseId; private String projectGroupName = ""; private String releaseGoal; public String execute() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); try { releaseManager.releaseRollback( releaseId, projectId ); } catch ( ContinuumReleaseException e ) { if ( e.getMessage() != null ) { addActionError( e.getMessage() ); return RELEASE_ERROR; } else { throw e; } } catch ( BuildAgentConfigurationException e ) { addActionError( "Error with configuration of build agent: " + e.getMessage() ); return RELEASE_ERROR; } } else { ContinuumReleaseManager releaseManager = getContinuum().getReleaseManager(); ContinuumReleaseManagerListener listener = new DefaultReleaseManagerListener(); listener.setUsername( getPrincipal() ); Project project = getContinuum().getProject( projectId ); releaseManager.rollback( releaseId, workingDirectoryService.getWorkingDirectory( project ).getPath(), listener ); //recurse until rollback is finished while ( listener.getState() != ContinuumReleaseManagerListener.FINISHED ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { //do nothing } } AuditLog event = new AuditLog( "Release id=" + releaseId, AuditLogConstants.ROLLBACK_RELEASE ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); releaseManager.getPreparedReleases().remove( releaseId ); } return SUCCESS; } public String warn() throws Exception { try { checkBuildProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } return SUCCESS; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getReleaseId() { return releaseId; } public void setReleaseId( String releaseId ) { this.releaseId = releaseId; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } public String getReleaseGoal() { return releaseGoal; } public void setReleaseGoal( String releaseGoal ) { this.releaseGoal = releaseGoal; } }
5,512
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectEditAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "projectEdit", instantiationStrategy = "per-lookup" ) public class ProjectEditAction extends ContinuumActionSupport { private Project project; private int projectId; private String name; private String version; private String scmUrl; private String scmUsername; private String scmPassword; private String scmTag; private boolean scmUseCache; public String save() throws ContinuumException { try { checkModifyProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } project = getProject( projectId ); project.setName( name ); project.setVersion( version ); project.setScmUrl( scmUrl ); project.setScmUseCache( scmUseCache ); project.setScmUsername( scmUsername ); project.setScmPassword( scmPassword ); project.setScmTag( scmTag ); getContinuum().updateProject( project ); AuditLog event = new AuditLog( "Project id=" + projectId, AuditLogConstants.MODIFY_PROJECT ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } public String edit() throws ContinuumException { try { checkModifyProjectInGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } project = getProject( projectId ); name = project.getName(); version = project.getVersion(); scmUrl = project.getScmUrl(); scmUsername = project.getScmUsername(); scmPassword = project.getScmPassword(); scmUseCache = project.isScmUseCache(); scmTag = project.getScmTag(); return SUCCESS; } private Project getProject( int projectId ) throws ContinuumException { return getContinuum().getProject( projectId ); } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getVersion() { return version; } public void setVersion( String version ) { this.version = version; } public String getScmUrl() { return scmUrl; } public void setScmUrl( String scmUrl ) { this.scmUrl = scmUrl; } public String getScmUsername() { return scmUsername; } public void setScmUsername( String scmUsername ) { this.scmUsername = scmUsername; } public String getScmPassword() { return scmPassword; } public void setScmPassword( String scmPassword ) { this.scmPassword = scmPassword; } public String getScmTag() { return scmTag; } public void setScmTag( String scmTag ) { this.scmTag = scmTag; } public Project getProject() { return project; } public void setScmUseCache( boolean scmUseCache ) { this.scmUseCache = scmUseCache; } public boolean isScmUseCache() { return scmUseCache; } public String getProjectGroupName() throws ContinuumException { return getProject( projectId ).getProjectGroup().getName(); } }
5,513
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/AddMavenOneProjectAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.codehaus.plexus.component.annotations.Component; import java.io.File; /** * Add a Maven 1 project to Continuum. * * @author Nick Gonzalez * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "addMavenOneProject", instantiationStrategy = "per-lookup" ) public class AddMavenOneProjectAction extends AddMavenProjectAction { protected ContinuumProjectBuildingResult doExecute( String pomUrl, int selectedProjectGroup, boolean checkProtocol, boolean scmUseCache ) throws ContinuumException { ContinuumProjectBuildingResult result = getContinuum().addMavenOneProject( pomUrl, selectedProjectGroup, checkProtocol, scmUseCache, this.getBuildDefinitionTemplateId() ); AuditLog event = new AuditLog( hidePasswordInUrl( pomUrl ), AuditLogConstants.ADD_M1_PROJECT ); event.setCategory( AuditLogConstants.PROJECT ); event.setCurrentUser( getPrincipal() ); if ( result == null || result.hasErrors() ) { event.setAction( AuditLogConstants.ADD_M1_PROJECT_FAILED ); } event.log(); return result; } /** * @deprecated Use {@link #getPom()} instead */ public String getM1Pom() { return getPom(); } /** * @deprecated Use {@link #setPom(String)} instead */ public void setM1Pom( String pom ) { setPom( pom ); } /** * @deprecated Use {@link #getPomFile()} instead */ public File getM1PomFile() { return getPomFile(); } /** * @deprecated Use {@link #setPomFile(File)} instead */ public void setM1PomFile( File pomFile ) { setPomFile( pomFile ); } /** * @deprecated Use {@link #getPomUrl()} instead */ public String getM1PomUrl() { return getPomUrl(); } /** * @deprecated Use {@link #setPomUrl(String)} instead */ public void setM1PomUrl( String pomUrl ) { setPomUrl( pomUrl ); } }
5,514
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/DeleteProjectAction.java
package org.apache.maven.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "deleteProject", instantiationStrategy = "per-lookup" ) public class DeleteProjectAction extends ContinuumActionSupport { private Logger logger = LoggerFactory.getLogger( this.getClass() ); private int projectId; private String projectName; private int projectGroupId; private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkRemoveProjectFromGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } AuditLog event = new AuditLog( "Project id=" + projectId, AuditLogConstants.REMOVE_PROJECT ); event.setCurrentUser( getPrincipal() ); event.setCategory( AuditLogConstants.PROJECT ); event.log(); try { getContinuum().removeProject( projectId ); } catch ( ContinuumException e ) { logger.error( "Error removing project with id " + projectId, e ); addActionError( getText( "deleteProject.error", "Unable to delete project", new Integer( projectId ).toString() ) ); } return SUCCESS; } public String doDefault() throws ContinuumException { try { checkRemoveProjectFromGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } Project project = getContinuum().getProject( projectId ); projectName = project.getName(); return "delete"; } public void setProjectId( int projectId ) { this.projectId = projectId; } public int getProjectId() { return projectId; } public void setProjectName( String projectName ) { this.projectName = projectName; } public String getProjectName() { return projectName; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getProjectGroupId() { return projectGroupId; } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { ProjectGroup group = getContinuum().getProjectGroupByProjectId( projectId ); projectGroupName = group.getName(); projectGroupId = group.getId(); } } return projectGroupName; } }
5,515
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/AbstractGroupNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.util.StringUtils; /** * Common base class for all Project Group notifier edit actions. * * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a> */ public abstract class AbstractGroupNotifierEditAction extends AbstractNotifierEditActionSupport { /** * {@link ProjectGroup} identifier for which the notifier is being edited. */ private int projectGroupId; private String projectGroupName = ""; /** * Creates or updates the {@link ProjectNotifier} instance for the * {@link ProjectGroup} here.<p> * This is used by the subclasses that create/obtain an instance of * {@link ProjectNotifier} to be saved. * * @see org.apache.maven.continuum.web.action.notifier.AbstractNotifierEditActionSupport#saveNotifier(ProjectNotifier) */ protected void saveNotifier( ProjectNotifier notifier ) throws ContinuumException { boolean isNew = notifier.getId() <= 0; if ( !isNew ) { getContinuum().updateGroupNotifier( projectGroupId, notifier ); } else { getContinuum().addGroupNotifier( projectGroupId, notifier ); } } /** * @return the notifier * @throws ContinuumException */ protected ProjectNotifier getNotifier() throws ContinuumException { return getContinuum().getGroupNotifier( projectGroupId, getNotifierId() ); } /** * @return the projectGroupId */ public int getProjectGroupId() { return projectGroupId; } /** * @param projectGroupId the projectGroupId to set */ public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } protected void checkAuthorization() throws AuthorizationRequiredException, ContinuumException { if ( getNotifier() == null ) { checkAddProjectGroupNotifierAuthorization( getProjectGroupName() ); } else { checkModifyProjectGroupNotifierAuthorization( getProjectGroupName() ); } } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } return projectGroupName; } }
5,516
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/MailProjectNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'Mail' from the * specified {@link Project}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "mailProjectNotifierEdit", instantiationStrategy = "per-lookup" ) public class MailProjectNotifierEditAction extends AbstractProjectNotifierEditAction { private String address; private boolean committers; private boolean developers; protected void initConfiguration( Map<String, String> configuration ) { if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ) ) ) { address = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); } if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.COMMITTER_FIELD ) ) ) { committers = Boolean.parseBoolean( configuration.get( AbstractContinuumNotifier.COMMITTER_FIELD ) ); } if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.DEVELOPER_FIELD ) ) ) { developers = Boolean.parseBoolean( configuration.get( AbstractContinuumNotifier.DEVELOPER_FIELD ) ); } } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, Object> configuration = new HashMap<String, Object>(); if ( StringUtils.isNotEmpty( address ) ) { configuration.put( AbstractContinuumNotifier.ADDRESS_FIELD, address ); } configuration.put( AbstractContinuumNotifier.COMMITTER_FIELD, String.valueOf( committers ) ); configuration.put( AbstractContinuumNotifier.DEVELOPER_FIELD, String.valueOf( developers ) ); notifier.setConfiguration( configuration ); } public String getAddress() { return address; } public void setAddress( String address ) { this.address = address; } public boolean isCommitters() { return committers; } public void setCommitters( boolean committers ) { this.committers = committers; } public boolean isDevelopers() { return developers; } public void setDevelopers( boolean developers ) { this.developers = developers; } }
5,517
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/DeleteProjectNotifierAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.GenerateRecipentNotifier; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; /** * Action that deletes a {@link ProjectNotifier} from a specified {@link Project}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "deleteProjectNotifier", instantiationStrategy = "per-lookup" ) public class DeleteProjectNotifierAction extends ContinuumActionSupport { private int projectId; /** * Identifier for the {@link ProjectGroup} that the current {@link Project} is a member of. */ private int projectGroupId; private int notifierId; private String notifierType; private String recipient; private boolean fromGroupPage = false; private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkRemoveProjectNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } getContinuum().removeNotifier( projectId, notifierId ); if ( fromGroupPage ) { return "to_group_page"; } return SUCCESS; } public String doDefault() throws ContinuumException { try { checkRemoveProjectNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } ProjectNotifier notifier = getContinuum().getNotifier( projectId, notifierId ); notifierType = notifier.getType(); recipient = GenerateRecipentNotifier.generate( notifier ); return "delete"; } public void setProjectId( int projectId ) { this.projectId = projectId; } public int getProjectId() { return projectId; } public void setNotifierId( int notifierId ) { this.notifierId = notifierId; } public int getNotifierId() { return notifierId; } public void setNotifierType( String notifierType ) { this.notifierType = notifierType; } public String getNotifierType() { return notifierType; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getRecipient() { return recipient; } public void setRecipient( String recipient ) { this.recipient = recipient; } public boolean isFromGroupPage() { return fromGroupPage; } public void setFromGroupPage( boolean fromGroupPage ) { this.fromGroupPage = fromGroupPage; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } } return projectGroupName; } }
5,518
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/WagonProjectNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'Wagon' from the * specified {@link Project}. * * @author <a href="mailto:hisidro@exist.com">Henry Isidro</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "wagonProjectNotifierEdit", instantiationStrategy = "per-lookup" ) public class WagonProjectNotifierEditAction extends AbstractProjectNotifierEditAction { private String url; private String id; protected void initConfiguration( Map<String, String> configuration ) { url = configuration.get( "url" ); id = configuration.get( "id" ); } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "url", url ); configuration.put( "id", id ); notifier.setConfiguration( configuration ); } public String getUrl() { return url; } public void setUrl( String url ) { this.url = url; } public String getId() { return id; } public void setId( String id ) { this.id = id; } }
5,519
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/DeleteGroupNotifierAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.GenerateRecipentNotifier; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; /** * Action to delete a {@link ProjectNotifier} instance from a * specified {@link ProjectGroup}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "deleteGroupNotifier", instantiationStrategy = "per-lookup" ) public class DeleteGroupNotifierAction extends ContinuumActionSupport { private int projectGroupId; private int notifierId; private String notifierType; private String recipient; private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkRemoveProjectGroupNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } getContinuum().removeGroupNotifier( projectGroupId, notifierId ); return SUCCESS; } public String doDefault() throws ContinuumException { try { checkRemoveProjectGroupNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } ProjectNotifier notifier = getContinuum().getGroupNotifier( projectGroupId, notifierId ); notifierType = notifier.getType(); recipient = GenerateRecipentNotifier.generate( notifier ); return "delete"; } public void setNotifierId( int notifierId ) { this.notifierId = notifierId; } public int getNotifierId() { return notifierId; } public void setNotifierType( String notifierType ) { this.notifierType = notifierType; } public String getNotifierType() { return notifierType; } /** * @return the projectGroupId */ public int getProjectGroupId() { return projectGroupId; } /** * @param projectGroupId the projectGroupId to set */ public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getProjectId() { //flags that this is a group notifier return -1; } public String getRecipient() { return recipient; } public void setRecipient( String recipient ) { this.recipient = recipient; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } return projectGroupName; } }
5,520
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/MsnProjectNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'MSN' from the * specified {@link Project}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "msnProjectNotifierEdit", instantiationStrategy = "per-lookup" ) public class MsnProjectNotifierEditAction extends AbstractProjectNotifierEditAction { private String login; private String password; private String address; protected void initConfiguration( Map<String, String> configuration ) { login = configuration.get( "login" ); password = configuration.get( "password" ); address = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "login", login ); configuration.put( "password", password ); configuration.put( AbstractContinuumNotifier.ADDRESS_FIELD, address ); notifier.setConfiguration( configuration ); } public String getLogin() { return login; } public void setLogin( String login ) { this.login = login; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public String getAddress() { return address; } public void setAddress( String address ) { this.address = address; } }
5,521
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/JabberGroupNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'Jabber' from the * specified {@link ProjectGroup}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "jabberGroupNotifierEdit", instantiationStrategy = "per-lookup" ) public class JabberGroupNotifierEditAction extends AbstractGroupNotifierEditAction { private String host; private int port = 5222; private String login; private String password; private String domainName; private String address; private boolean sslConnection; private boolean group; protected void initConfiguration( Map<String, String> configuration ) { host = configuration.get( "host" ); if ( configuration.get( "port" ) != null ) { port = Integer.parseInt( configuration.get( "port" ) ); } login = configuration.get( "login" ); password = configuration.get( "password" ); domainName = configuration.get( "domainName" ); address = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); sslConnection = Boolean.valueOf( configuration.get( "sslConnection" ) ); group = Boolean.valueOf( configuration.get( "isGroup" ) ); } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "host", host ); configuration.put( "port", String.valueOf( port ) ); configuration.put( "login", login ); configuration.put( "password", password ); configuration.put( "domainName", domainName ); configuration.put( AbstractContinuumNotifier.ADDRESS_FIELD, address ); configuration.put( "sslConnection", String.valueOf( sslConnection ) ); configuration.put( "isGroup", String.valueOf( group ) ); notifier.setConfiguration( configuration ); } public String getHost() { return host; } public void setHost( String host ) { this.host = host; } public int getPort() { return port; } public void setPort( int port ) { this.port = port; } public String getLogin() { return login; } public void setLogin( String login ) { this.login = login; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public String getDomainName() { return domainName; } public void setDomainName( String domainName ) { this.domainName = domainName; } public String getAddress() { return address; } public void setAddress( String address ) { this.address = address; } public boolean isSslConnection() { return sslConnection; } public void setSslConnection( boolean sslConnection ) { this.sslConnection = sslConnection; } public boolean isGroup() { return group; } public void setGroup( boolean group ) { this.group = group; } }
5,522
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/AddGroupNotifierAction.java
/** * */ package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; /** * WW action that sets up a new {@link ProjectNotifier} instance for * the specified {@link ProjectGroup}. * * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "addGroupNotifier", instantiationStrategy = "per-lookup" ) public class AddGroupNotifierAction extends ContinuumActionSupport { /** * Target {@link ProjectGroup} instance to add the Notifier for. */ private int projectGroupId; /** * String based type identifier for the {@link ProjectNotifier}. */ private String notifierType; private String projectGroupName = ""; /** * Default action method executed in case no method is specified * for invocation. * * @return a String result that determines the control flow. */ public String execute() throws ContinuumException { try { checkAddProjectGroupNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return notifierType + "_" + INPUT; } // TODO: Remove this method because a default method return SUCCESS instead of INPUT public String doDefault() throws ContinuumException { return input(); } public String input() throws ContinuumException { try { checkAddProjectGroupNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return INPUT; } /** * Returns the type identifier for the {@link ProjectNotifier} being * edited as String. * * @return notifier type as String. */ public String getNotifierType() { return notifierType; } /** * Sets the notifier type for the {@link ProjectNotifier} instance * being edited. * * @param notifierType notifier type to set. */ public void setNotifierType( String notifierType ) { this.notifierType = notifierType; } /** * Returns the current {@link ProjectGroup} Identifier. * * @return the projectGroupId */ public int getProjectGroupId() { return projectGroupId; } /** * Sets the Id for the target {@link ProjectGroup}. * * @param projectGroupId the projectGroupId to set */ public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } return projectGroupName; } }
5,523
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/JabberProjectNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'Jabber' from the * specified {@link Project}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "jabberProjectNotifierEdit", instantiationStrategy = "per-lookup" ) public class JabberProjectNotifierEditAction extends AbstractProjectNotifierEditAction { private String host; private int port = 5222; private String login; private String password; private String domainName; private String address; private boolean sslConnection; private boolean group; protected void initConfiguration( Map<String, String> configuration ) { host = configuration.get( "host" ); if ( configuration.get( "port" ) != null ) { port = Integer.parseInt( configuration.get( "port" ) ); } login = configuration.get( "login" ); password = configuration.get( "password" ); domainName = configuration.get( "domainName" ); address = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); sslConnection = Boolean.valueOf( configuration.get( "sslConnection" ) ); group = Boolean.valueOf( configuration.get( "isGroup" ) ); } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "host", host ); configuration.put( "port", String.valueOf( port ) ); configuration.put( "login", login ); configuration.put( "password", password ); configuration.put( "domainName", domainName ); configuration.put( AbstractContinuumNotifier.ADDRESS_FIELD, address ); configuration.put( "sslConnection", String.valueOf( sslConnection ) ); configuration.put( "isGroup", String.valueOf( group ) ); notifier.setConfiguration( configuration ); } public String getHost() { return host; } public void setHost( String host ) { this.host = host; } public int getPort() { return port; } public void setPort( int port ) { this.port = port; } public String getLogin() { return login; } public void setLogin( String login ) { this.login = login; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public String getDomainName() { return domainName; } public void setDomainName( String domainName ) { this.domainName = domainName; } public String getAddress() { return address; } public void setAddress( String address ) { this.address = address; } public boolean isSslConnection() { return sslConnection; } public void setSslConnection( boolean sslConnection ) { this.sslConnection = sslConnection; } public boolean isGroup() { return group; } public void setGroup( boolean group ) { this.group = group; } }
5,524
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/IrcProjectNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "ircProjectNotifierEdit", instantiationStrategy = "per-lookup" ) public class IrcProjectNotifierEditAction extends AbstractProjectNotifierEditAction { private String host; private int port = 6667; private String channel; private String nick; private String alternateNick; private String username; private String fullName; private String password; private boolean ssl = false; protected void initConfiguration( Map<String, String> configuration ) { host = configuration.get( "host" ); if ( configuration.get( "port" ) != null ) { port = Integer.parseInt( configuration.get( "port" ) ); } channel = configuration.get( "channel" ); nick = configuration.get( "nick" ); alternateNick = configuration.get( "alternateNick" ); username = configuration.get( "username" ); fullName = configuration.get( "fullName" ); password = configuration.get( "password" ); if ( configuration.get( "ssl" ) != null ) { ssl = Boolean.parseBoolean( configuration.get( "ssl" ) ); } } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "host", host ); configuration.put( "port", String.valueOf( port ) ); configuration.put( "channel", channel ); configuration.put( "nick", nick ); configuration.put( "alternateNick", alternateNick ); configuration.put( "username", username ); configuration.put( "fullName", fullName ); configuration.put( "password", password ); configuration.put( "ssl", String.valueOf( ssl ) ); notifier.setConfiguration( configuration ); } public String getHost() { return host; } public void setHost( String host ) { this.host = host; } public int getPort() { return port; } public void setPort( int port ) { this.port = port; } public String getChannel() { return channel; } public void setChannel( String channel ) { this.channel = channel; } public String getNick() { return nick; } public void setNick( String nick ) { this.nick = nick; } public String getAlternateNick() { return alternateNick; } public void setAlternateNick( String alternateNick ) { this.alternateNick = alternateNick; } public String getUsername() { return username; } public void setUsername( String username ) { this.username = username; } public String getFullName() { return fullName; } public void setFullName( String fullName ) { this.fullName = fullName; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public boolean isSsl() { return ssl; } public void setSsl( boolean ssl ) { this.ssl = ssl; } }
5,525
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/IrcGroupNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'IRC' from the * specified {@link ProjectGroup}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "ircGroupNotifierEdit", instantiationStrategy = "per-lookup" ) public class IrcGroupNotifierEditAction extends AbstractGroupNotifierEditAction { private String host; private int port = 6667; private String channel; private String nick; private String alternateNick; private String username; private String fullName; private String password; private boolean ssl = false; protected void initConfiguration( Map<String, String> configuration ) { host = configuration.get( "host" ); if ( configuration.get( "port" ) != null ) { port = Integer.parseInt( configuration.get( "port" ) ); } channel = configuration.get( "channel" ); nick = configuration.get( "nick" ); alternateNick = configuration.get( "alternateNick" ); username = configuration.get( "username" ); fullName = configuration.get( "fullName" ); password = configuration.get( "password" ); if ( configuration.get( "ssl" ) != null ) { ssl = Boolean.parseBoolean( configuration.get( "ssl" ) ); } } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "host", host ); configuration.put( "port", String.valueOf( port ) ); configuration.put( "channel", channel ); configuration.put( "nick", nick ); configuration.put( "alternateNick", alternateNick ); configuration.put( "username", username ); configuration.put( "fullName", fullName ); configuration.put( "password", password ); configuration.put( "ssl", String.valueOf( ssl ) ); notifier.setConfiguration( configuration ); } public String getHost() { return host; } public void setHost( String host ) { this.host = host; } public int getPort() { return port; } public void setPort( int port ) { this.port = port; } public String getChannel() { return channel; } public void setChannel( String channel ) { this.channel = channel; } public String getNick() { return nick; } public void setNick( String nick ) { this.nick = nick; } public String getAlternateNick() { return alternateNick; } public void setAlternateNick( String alternateNick ) { this.alternateNick = alternateNick; } public String getUsername() { return username; } public void setUsername( String username ) { this.username = username; } public String getFullName() { return fullName; } public void setFullName( String fullName ) { this.fullName = fullName; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public boolean isSsl() { return ssl; } public void setSsl( boolean ssl ) { this.ssl = ssl; } }
5,526
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/WagonGroupNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'Wagon' from the * specified {@link ProjectGroup}. * * @author <a href="mailto:hisidro@exist.com">Henry Isidro</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "wagonGroupNotifierEdit", instantiationStrategy = "per-lookup" ) public class WagonGroupNotifierEditAction extends AbstractGroupNotifierEditAction { private String url; private String id; protected void initConfiguration( Map<String, String> configuration ) { url = configuration.get( "url" ); id = configuration.get( "id" ); } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "url", url ); configuration.put( "id", id ); notifier.setConfiguration( configuration ); } public String getUrl() { return url; } public void setUrl( String url ) { this.url = url; } public String getId() { return id; } public void setId( String id ) { this.id = id; } }
5,527
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/AddProjectNotifierAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; /** * Action to add a {@link ProjectNotifier} for a specified {@link Project}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "addProjectNotifier", instantiationStrategy = "per-lookup" ) public class AddProjectNotifierAction extends ContinuumActionSupport { /** * Identifier for the {@link Project} instance. */ private int projectId; /** * Identifier for the {@link ProjectGroup} instance that the current {@link Project} is a member of. */ private int projectGroupId; /** * Type for a {@link ProjectNotifier}. */ private String notifierType; /** * Detemines if the save operation returns to the project group notifier page or not.<p> * <code>true</code> implies return to the project group notifier page. */ private boolean fromGroupPage = false; private String projectGroupName = ""; /** * Default method executed when no specific method is specified * for invocation. * * @return result as a String value to determines the control flow. */ public String execute() throws ContinuumException { try { checkAddProjectNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return notifierType + "_" + INPUT; } // TODO: Remove this method because a default method return SUCCESS instead of INPUT public String doDefault() throws ContinuumException { return input(); } public String input() throws ContinuumException { try { checkAddProjectNotifierAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return INPUT; } /** * Returns the type for the {@link ProjectNotifier}. * * @return Notifier type as String. */ public String getNotifierType() { return notifierType; } /** * Sets the type for the {@link ProjectNotifier}. * * @param notifierType Notifier type to set. */ public void setNotifierType( String notifierType ) { this.notifierType = notifierType; } /** * Identifier for the Project being edited. * * @return project id. */ public int getProjectId() { return projectId; } /** * Sets the identifier for the Project to be edited for * project notifiers. * * @param projectId The project id to set. */ public void setProjectId( int projectId ) { this.projectId = projectId; } /** * Returns the identifier for the {@link ProjectGroup} that the * {@link Project} is a member of. * * @return the projectGroupId */ public int getProjectGroupId() { return projectGroupId; } /** * Sets the identifier for the {@link ProjectGroup} that the * {@link Project} is a member of. * * @param projectGroupId the identifier to set */ public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } /** * @return the fromGroupPage */ public boolean isFromGroupPage() { return fromGroupPage; } /** * @param fromGroupPage the fromGroupPage to set */ public void setFromGroupPage( boolean fromGroupPage ) { this.fromGroupPage = fromGroupPage; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } } return projectGroupName; } }
5,528
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/MsnGroupNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.component.annotations.Component; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'MSN' from the * specified {@link ProjectGroup}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "msnGroupNotifierEdit", instantiationStrategy = "per-lookup" ) public class MsnGroupNotifierEditAction extends AbstractGroupNotifierEditAction { private String login; private String password; private String address; protected void initConfiguration( Map<String, String> configuration ) { login = configuration.get( "login" ); password = configuration.get( "password" ); address = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put( "login", login ); configuration.put( "password", password ); configuration.put( AbstractContinuumNotifier.ADDRESS_FIELD, address ); notifier.setConfiguration( configuration ); } public String getLogin() { return login; } public void setLogin( String login ) { this.login = login; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public String getAddress() { return address; } public void setAddress( String address ) { this.address = address; } }
5,529
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/AbstractNotifierEditActionSupport.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import java.util.Map; /** * Common base class that consolidates the common properties used by extending * <code>XXXEditAction</code> implementations and defines a contract expected of * the extending clases. * * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a> * @since 1.1 */ public abstract class AbstractNotifierEditActionSupport extends ContinuumActionSupport { /** * Identifier for the {@link ProjectNotifier} instance being edited. */ private int notifierId; /** * Type of {@link ProjectNotifier} tagged as a String value. */ private String notifierType; /** * Detemines if the notifier should fire when build was successful.<p> * <code>true</code> implies notifier executes on a successful build. */ private boolean sendOnSuccess; /** * Detemines if the notifier should fire when build failed.<p> * <code>true</code> implies notifier executes for a failed build. */ private boolean sendOnFailure; /** * Detemines if the notifier should fire when build resulted in any error(s).<p> * <code>true</code> implies notifier executes when any error(s) is/are detected * for the build. */ private boolean sendOnError; /** * Detemines if the notifier should fire when build resulted in any warning(s).<p> * <code>true</code> implies notifier executes when any warning(s) is/are detected * for the build. */ private boolean sendOnWarning; /** * Detemines if the notifier should fire when prepare build resulted in any error(s).<p> * <code>true</code> implies notifier executes when any error(s) is/are detected * for the build. */ private boolean sendOnScmFailure; /** * Detemines if the save operation returns to the project group notifier page or not.<p> * <code>true</code> implies return to the project group notifier page. */ private boolean fromGroupPage = false; /** * Obtain and return the {@link ProjectNotifier} instance for editing. * * @return {@link ProjectNotifier} instance. * @throws ContinuumException if there was error retrieving the target {@link ProjectNotifier} instance. */ protected abstract ProjectNotifier getNotifier() throws ContinuumException; /** * Persists update to the {@link ProjectNotifier} instance being edited. * * @param notifier {@link ProjectNotifier} to save. * @throws ContinuumException if there was an error saving the * {@link ProjectNotifier} instance. */ protected abstract void saveNotifier( ProjectNotifier notifier ) throws ContinuumException; /** * Creates or updates {@link ProjectNotifier} instance. * * @return result as String. * @throws ContinuumException */ public String save() throws ContinuumException { try { checkAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } ProjectNotifier notifier = getNotifier(); boolean isNew = ( notifier == null || getNotifierId() == 0 ); if ( isNew ) { notifier = new ProjectNotifier(); } notifier.setType( getNotifierType() ); notifier.setSendOnSuccess( isSendOnSuccess() ); notifier.setSendOnFailure( isSendOnFailure() ); notifier.setSendOnError( isSendOnError() ); notifier.setSendOnWarning( isSendOnWarning() ); notifier.setSendOnScmFailure( isSendOnScmFailure() ); setNotifierConfiguration( notifier ); saveNotifier( notifier ); if ( fromGroupPage ) { return "to_group_page"; } return SUCCESS; } /** * Obtains the {@link ProjectNotifier} instance for edit purposes. * * @return result as String. * @throws ContinuumException */ public String edit() throws ContinuumException { ProjectNotifier notifier = getNotifier(); if ( notifier == null ) { notifier = new ProjectNotifier(); } try { checkAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } // setup Action fields setNotifierType( notifier.getType() ); setSendOnSuccess( notifier.isSendOnSuccess() ); setSendOnFailure( notifier.isSendOnFailure() ); setSendOnError( notifier.isSendOnError() ); setSendOnWarning( notifier.isSendOnWarning() ); setSendOnScmFailure( notifier.isSendOnScmFailure() ); initConfiguration( notifier.getConfiguration() ); return SUCCESS; } public int getNotifierId() { return notifierId; } /** * @return the notifierType */ public String getNotifierType() { return notifierType; } /** * @param notifierType the notifierType to set */ public void setNotifierType( String notifierType ) { this.notifierType = notifierType; } /** * @return the sendOnSuccess */ public boolean isSendOnSuccess() { return sendOnSuccess; } /** * @param sendOnSuccess the sendOnSuccess to set */ public void setSendOnSuccess( boolean sendOnSuccess ) { this.sendOnSuccess = sendOnSuccess; } /** * @return the sendOnFailure */ public boolean isSendOnFailure() { return sendOnFailure; } /** * @param sendOnFailure the sendOnFailure to set */ public void setSendOnFailure( boolean sendOnFailure ) { this.sendOnFailure = sendOnFailure; } /** * @return the sendOnError */ public boolean isSendOnError() { return sendOnError; } /** * @param sendOnError the sendOnError to set */ public void setSendOnError( boolean sendOnError ) { this.sendOnError = sendOnError; } /** * @return the sendOnWarning */ public boolean isSendOnWarning() { return sendOnWarning; } /** * @param sendOnWarning the sendOnWarning to set */ public void setSendOnWarning( boolean sendOnWarning ) { this.sendOnWarning = sendOnWarning; } public boolean isSendOnScmFailure() { return sendOnScmFailure; } public void setSendOnScmFailure( boolean sendOnScmFailure ) { this.sendOnScmFailure = sendOnScmFailure; } /** * @param notifierId the notifierId to set */ public void setNotifierId( int notifierId ) { this.notifierId = notifierId; } /** * @return the fromGroupPage */ public boolean isFromGroupPage() { return fromGroupPage; } /** * @param fromGroupPage the fromGroupPage to set */ public void setFromGroupPage( boolean fromGroupPage ) { this.fromGroupPage = fromGroupPage; } /** * Initialises the configuration map that the {@link ProjectNotifier} * instance is to be inited with. * * @param configuration map of configuration key-value pairs. */ protected abstract void initConfiguration( Map<String, String> configuration ); /** * Sets the configuration for the specified {@link ProjectNotifier} * instance. * * @param notifier The project notifier. * @see #initConfiguration(Map) */ protected abstract void setNotifierConfiguration( ProjectNotifier notifier ); protected abstract void checkAuthorization() throws AuthorizationRequiredException, ContinuumException; }
5,530
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/AbstractProjectNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public abstract class AbstractProjectNotifierEditAction extends AbstractNotifierEditActionSupport { /** * Identifier for the {@link Project} who's {@link ProjectNotifier} is being edited. */ private int projectId; /** * Identifier for the {@link ProjectGroup} instance that the current {@link Project} is a member of. */ private int projectGroupId; private String projectGroupName = ""; /** * Save the notifier for the {@link Project} here.<p> * This is used by the subclasses that create/obtain an instance of * {@link ProjectNotifier} to be saved. * * @see org.apache.maven.continuum.web.action.notifier.AbstractNotifierEditActionSupport#saveNotifier(ProjectNotifier) */ protected void saveNotifier( ProjectNotifier notifier ) throws ContinuumException { boolean isNew = notifier.getId() <= 0; if ( !isNew ) { getContinuum().updateNotifier( projectId, notifier ); } else { getContinuum().addNotifier( projectId, notifier ); } } /** * @see org.apache.maven.continuum.web.action.notifier.AbstractNotifierEditActionSupport#getNotifier() */ protected ProjectNotifier getNotifier() throws ContinuumException { return getContinuum().getNotifier( projectId, getNotifierId() ); } /** * Returns the identifier for the current project. * * @return current project's id. */ public int getProjectId() { return projectId; } /** * Sets the id of the current project for this action. * * @param projectId current project's id. */ public void setProjectId( int projectId ) { this.projectId = projectId; } /** * Returns the identifier for the {@link ProjectGroup} that the * {@link Project} is a member of. * * @return the projectGroupId */ public int getProjectGroupId() { return projectGroupId; } /** * Sets the identifier for the {@link ProjectGroup} that the * {@link Project} is a member of. * * @param projectGroupId the identifier to set */ public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } protected void checkAuthorization() throws AuthorizationRequiredException, ContinuumException { if ( getNotifier() == null ) { checkAddProjectNotifierAuthorization( getProjectGroupName() ); } else { checkModifyProjectNotifierAuthorization( getProjectGroupName() ); } } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } } return projectGroupName; } }
5,531
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/notifier/MailGroupNotifierEditAction.java
package org.apache.maven.continuum.web.action.notifier; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import java.util.HashMap; import java.util.Map; /** * Action that edits a {@link ProjectNotifier} of type 'Mail' from the * specified {@link ProjectGroup}. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @since 1.1 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "mailGroupNotifierEdit", instantiationStrategy = "per-lookup" ) public class MailGroupNotifierEditAction extends AbstractGroupNotifierEditAction { private String address; private boolean committers; private boolean developers; protected void initConfiguration( Map<String, String> configuration ) { if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ) ) ) { address = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); } if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.COMMITTER_FIELD ) ) ) { committers = Boolean.parseBoolean( configuration.get( AbstractContinuumNotifier.COMMITTER_FIELD ) ); } if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.DEVELOPER_FIELD ) ) ) { developers = Boolean.parseBoolean( configuration.get( AbstractContinuumNotifier.DEVELOPER_FIELD ) ); } } protected void setNotifierConfiguration( ProjectNotifier notifier ) { HashMap<String, Object> configuration = new HashMap<String, Object>(); if ( StringUtils.isNotEmpty( address ) ) { configuration.put( AbstractContinuumNotifier.ADDRESS_FIELD, address ); } configuration.put( AbstractContinuumNotifier.COMMITTER_FIELD, String.valueOf( committers ) ); configuration.put( AbstractContinuumNotifier.DEVELOPER_FIELD, String.valueOf( developers ) ); notifier.setConfiguration( configuration ); } public String getAddress() { return address; } public void setAddress( String address ) { this.address = address; } public boolean isCommitters() { return committers; } public void setCommitters( boolean committers ) { this.committers = committers; } public boolean isDevelopers() { return developers; } public void setDevelopers( boolean developers ) { this.developers = developers; } }
5,532
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/ProfileAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.commons.lang.StringUtils; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.profile.AlreadyExistsProfileException; import org.apache.maven.continuum.profile.ProfileException; import org.apache.maven.continuum.profile.ProfileService; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * @since 7 juin 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "profileAdministration", instantiationStrategy = "per-lookup" ) public class ProfileAction extends ContinuumActionSupport implements Preparable, SecureAction { private static final Logger logger = LoggerFactory.getLogger( ProfileAction.class ); @Requirement( hint = "default" ) private ProfileService profileService; @Requirement( hint = "default" ) private InstallationService installationService; private List<Profile> profiles; private Profile profile; private int installationId; private List<Installation> allInstallations; private List<Installation> profileInstallations; private List<BuildAgentGroupConfiguration> buildAgentGroups; public void prepare() throws Exception { super.prepare(); List<BuildAgentGroupConfiguration> agentGroups = getContinuum().getConfiguration().getBuildAgentGroups(); if ( agentGroups == null ) { agentGroups = Collections.EMPTY_LIST; } this.setBuildAgentGroups( agentGroups ); } // ------------------------------------------------------- // Webwork Methods // ------------------------------------------------------- public String input() throws Exception { this.allInstallations = installationService.getAllInstallations(); return INPUT; } public String list() throws Exception { this.profiles = profileService.getAllProfiles(); return SUCCESS; } public String edit() throws Exception { if ( logger.isDebugEnabled() ) { logger.debug( "edit profile with id " + profile.getId() ); } this.profile = profileService.getProfile( profile.getId() ); return SUCCESS; } public String save() throws Exception { try { Profile stored = profileService.getProfile( profile.getId() ); if ( StringUtils.isBlank( profile.getName() ) ) { if ( stored != null ) { profile = stored; } this.addFieldError( "profile.name", getResourceBundle().getString( "profile.name.required" ) ); return INPUT; } if ( stored == null ) { this.profile = profileService.addProfile( profile ); this.allInstallations = installationService.getAllInstallations(); return "editProfile"; } else { // olamy : the only thing to change here is the profile name // but in the UI maybe some installations has been we retrieve it // and only set the name related to CONTINUUM-1361 String name = profile.getName(); String buildAgentGroup = profile.getBuildAgentGroup(); profile = profileService.getProfile( profile.getId() ); // CONTINUUM-1746 we update the profile only if the name has changed // jancajas: added build agent group. updated profile if agent group is changed also. if ( !StringUtils.equals( name, profile.getName() ) || !StringUtils.equals( buildAgentGroup, profile.getBuildAgentGroup() ) ) { profile.setName( name ); profile.setBuildAgentGroup( buildAgentGroup ); profileService.updateProfile( profile ); } } } catch ( AlreadyExistsProfileException e ) { this.addActionError( getResourceBundle().getString( "profile.name.already.exists" ) ); return INPUT; } this.profiles = profileService.getAllProfiles(); return SUCCESS; } public String delete() throws Exception { try { profileService.deleteProfile( profile.getId() ); this.profiles = profileService.getAllProfiles(); } catch ( ProfileException e ) { // display action error in default/success page -- CONTINUUM-2250 addActionError( getText( "profile.remove.error" ) ); } return SUCCESS; } public String confirmDelete() throws ProfileException { this.profile = getContinuum().getProfileService().getProfile( profile.getId() ); return SUCCESS; } public String addInstallation() throws Exception { Installation installation = installationService.getInstallation( this.getInstallationId() ); if ( installation != null ) { profileService.addInstallationInProfile( profile, installation ); // read again this.profile = profileService.getProfile( profile.getId() ); } return SUCCESS; } public String removeInstallation() throws Exception { Installation installation = installationService.getInstallation( this.getInstallationId() ); profileService.removeInstallationFromProfile( profile, installation ); this.profile = profileService.getProfile( profile.getId() ); return SUCCESS; } // ----------------------------------------------------- // security // ----------------------------------------------------- public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PROFILES, Resource.GLOBAL ); return bundle; } // ------------------------------------------------------- // Webwork setter/getter // ------------------------------------------------------- public List<Profile> getProfiles() { return profiles; } public void setProfiles( List<Profile> profiles ) { this.profiles = profiles; } public Profile getProfile() { return profile; } public void setProfile( Profile profile ) { this.profile = profile; } public List<Installation> getAllInstallations() throws Exception { if ( this.allInstallations == null ) { this.allInstallations = installationService.getAllInstallations(); } // CONTINUUM-1742 (olamy) don't display already attached en var if ( this.profile != null ) { this.allInstallations.removeAll( this.profile.getEnvironmentVariables() ); } return allInstallations; } public void setAllInstallations( List<Installation> allInstallations ) { this.allInstallations = allInstallations; } public List<Installation> getProfileInstallations() { if ( this.profile != null ) { if ( this.profileInstallations == null ) { this.profileInstallations = new ArrayList<Installation>(); if ( this.profile.getJdk() != null ) { this.profileInstallations.add( this.profile.getJdk() ); } if ( this.profile.getBuilder() != null ) { this.profileInstallations.add( this.profile.getBuilder() ); } if ( this.profile.getEnvironmentVariables() != null && !this.profile.getEnvironmentVariables().isEmpty() ) { this.profileInstallations.addAll( this.profile.getEnvironmentVariables() ); } } return profileInstallations; } return Collections.EMPTY_LIST; } public void setProfileInstallations( List<Installation> profileInstallations ) { this.profileInstallations = profileInstallations; } public int getInstallationId() { return installationId; } public void setInstallationId( int installationId ) { this.installationId = installationId; } public List<BuildAgentGroupConfiguration> getBuildAgentGroups() { return buildAgentGroups; } public void setBuildAgentGroups( List<BuildAgentGroupConfiguration> buildAgentGroups ) { this.buildAgentGroups = buildAgentGroups; } }
5,533
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/ConfigureFooterAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.web.action.component.AbstractFooterAction; import org.apache.maven.continuum.web.appareance.AppareanceConfiguration; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.IOException; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 9 nov. 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "configureFooter", instantiationStrategy = "per-lookup" ) public class ConfigureFooterAction extends AbstractFooterAction { @Requirement private AppareanceConfiguration appareanceConfiguration; public String saveFooter() throws IOException { appareanceConfiguration.saveFooter( getFooter() ); addActionMessage( getResourceBundle().getString( "appearance.footerContent.success" ) ); return SUCCESS; } }
5,534
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/QueuesAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.ArrayUtils; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.CheckOutTask; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.bean.BuildProjectQueue; import org.apache.maven.continuum.web.bean.CheckoutQueue; import org.apache.maven.continuum.web.exception.AuthenticationRequiredException; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.model.DistributedBuildSummary; import org.apache.maven.continuum.web.model.PrepareBuildSummary; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 24 sept. 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "queues", instantiationStrategy = "per-lookup" ) public class QueuesAction extends ContinuumActionSupport implements SecureAction { private static final Logger logger = LoggerFactory.getLogger( QueuesAction.class ); private static final String DISTRIBUTED_BUILD_SUCCESS = "distributed-build-success"; private List<String> selectedPrepareBuildTaskHashCodes; private List<String> selectedBuildTaskHashCodes; private List<String> selectedCheckOutTaskHashCodes; private int buildDefinitionId; private int projectId; private int trigger; private String projectName; private List<BuildProjectQueue> currentBuildProjectTasks = new ArrayList<BuildProjectQueue>(); private List<CheckoutQueue> currentCheckoutTasks = new ArrayList<CheckoutQueue>(); private List<BuildProjectQueue> buildsInQueue = new ArrayList<BuildProjectQueue>(); private List<CheckoutQueue> checkoutsInQueue = new ArrayList<CheckoutQueue>(); private List<PrepareBuildSummary> currentPrepareBuilds = new ArrayList<PrepareBuildSummary>(); private List<PrepareBuildSummary> prepareBuildQueues = new ArrayList<PrepareBuildSummary>(); private List<PrepareBuildSummary> currentDistributedPrepareBuilds = new ArrayList<PrepareBuildSummary>(); private List<PrepareBuildSummary> distributedPrepareBuildQueues = new ArrayList<PrepareBuildSummary>(); private List<DistributedBuildSummary> currentDistributedBuilds = new ArrayList<DistributedBuildSummary>(); private List<DistributedBuildSummary> distributedBuildQueues = new ArrayList<DistributedBuildSummary>(); private String buildAgentUrl; private int projectGroupId; private int scmRootId; // ----------------------------------------------------- // webwork // ----------------------------------------------------- public String cancelCurrent() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } try { getContinuum().getBuildsManager().cancelBuild( projectId ); } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } return SUCCESS; } public String removeCheckout() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } try { getContinuum().getBuildsManager().removeProjectFromCheckoutQueue( projectId ); } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } return SUCCESS; } public String cancelCurrentCheckout() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } try { cancelCheckout( projectId ); } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } return SUCCESS; } public String display() throws Exception { if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { // current prepare build task Map<String, PrepareBuildProjectsTask> currentPrepareBuildMap = getContinuum().getDistributedBuildManager().getProjectsCurrentlyPreparingBuild(); for ( String url : currentPrepareBuildMap.keySet() ) { PrepareBuildProjectsTask task = currentPrepareBuildMap.get( url ); ProjectGroup projectGroup = getContinuum().getProjectGroup( task.getProjectGroupId() ); PrepareBuildSummary summary = new PrepareBuildSummary(); summary.setBuildAgentUrl( url ); summary.setProjectGroupId( task.getProjectGroupId() ); summary.setProjectGroupName( projectGroup.getName() ); summary.setScmRootAddress( task.getScmRootAddress() ); summary.setScmRootId( task.getProjectScmRootId() ); currentDistributedPrepareBuilds.add( summary ); } // current builds Map<String, BuildProjectTask> currentBuildMap = getContinuum().getDistributedBuildManager().getProjectsCurrentlyBuilding(); for ( String url : currentBuildMap.keySet() ) { BuildProjectTask task = currentBuildMap.get( url ); Project project = getContinuum().getProject( task.getProjectId() ); DistributedBuildSummary summary = new DistributedBuildSummary(); summary.setProjectId( project.getId() ); summary.setProjectName( project.getName() ); summary.setProjectGroupName( project.getProjectGroup().getName() ); summary.setBuildDefinitionId( task.getBuildDefinitionId() ); summary.setBuildDefinitionLabel( task.getBuildDefinitionLabel() ); summary.setHashCode( task.getHashCode() ); summary.setBuildAgentUrl( url ); summary.setTriggeredBy( task.getBuildTrigger().getTriggeredBy() ); currentDistributedBuilds.add( summary ); } // prepare build queues Map<String, List<PrepareBuildProjectsTask>> prepareBuildMap = getContinuum().getDistributedBuildManager().getProjectsInPrepareBuildQueue(); for ( String url : prepareBuildMap.keySet() ) { for ( PrepareBuildProjectsTask task : prepareBuildMap.get( url ) ) { ProjectGroup projectGroup = getContinuum().getProjectGroup( task.getProjectGroupId() ); PrepareBuildSummary summary = new PrepareBuildSummary(); summary.setBuildAgentUrl( url ); summary.setProjectGroupId( task.getProjectGroupId() ); summary.setProjectGroupName( projectGroup.getName() ); summary.setScmRootAddress( task.getScmRootAddress() ); summary.setScmRootId( task.getProjectScmRootId() ); summary.setHashCode( task.getHashCode() ); distributedPrepareBuildQueues.add( summary ); } } // build queues Map<String, List<BuildProjectTask>> buildMap = getContinuum().getDistributedBuildManager().getProjectsInBuildQueue(); for ( String url : buildMap.keySet() ) { for ( BuildProjectTask task : buildMap.get( url ) ) { DistributedBuildSummary summary = new DistributedBuildSummary(); Project project = getContinuum().getProject( task.getProjectId() ); summary.setProjectId( project.getId() ); summary.setProjectName( project.getName() ); summary.setProjectGroupName( project.getProjectGroup().getName() ); summary.setBuildDefinitionId( task.getBuildDefinitionId() ); summary.setBuildDefinitionLabel( task.getBuildDefinitionLabel() ); summary.setHashCode( task.getHashCode() ); summary.setBuildAgentUrl( url ); summary.setTriggeredBy( task.getBuildTrigger().getTriggeredBy() ); distributedBuildQueues.add( summary ); } } return DISTRIBUTED_BUILD_SUCCESS; } else { try { // current prepare builds Map<String, PrepareBuildProjectsTask> currentPrepareBuildTasks = getContinuum().getBuildsManager().getCurrentProjectInPrepareBuild(); Set<String> keySet = currentPrepareBuildTasks.keySet(); for ( String key : keySet ) { PrepareBuildProjectsTask prepareBuildTask = currentPrepareBuildTasks.get( key ); PrepareBuildSummary s = new PrepareBuildSummary(); s.setProjectGroupId( prepareBuildTask.getProjectGroupId() ); s.setProjectGroupName( prepareBuildTask.getProjectGroupName() ); s.setScmRootId( prepareBuildTask.getProjectScmRootId() ); s.setScmRootAddress( prepareBuildTask.getScmRootAddress() ); s.setQueueName( key ); currentPrepareBuilds.add( s ); } } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } try { // current builds Map<String, BuildProjectTask> currentBuilds = getContinuum().getBuildsManager().getCurrentBuilds(); Set<String> keySet = currentBuilds.keySet(); for ( String key : keySet ) { BuildProjectTask buildTask = currentBuilds.get( key ); BuildProjectQueue queue = new BuildProjectQueue(); queue.setName( key ); queue.setTask( buildTask ); currentBuildProjectTasks.add( queue ); } } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } try { // queued prepare builds Map<String, List<PrepareBuildProjectsTask>> prepareBuilds = getContinuum().getBuildsManager().getProjectsInPrepareBuildQueue(); Set<String> keySet = prepareBuilds.keySet(); for ( String key : keySet ) { for ( PrepareBuildProjectsTask task : prepareBuilds.get( key ) ) { PrepareBuildSummary summary = new PrepareBuildSummary(); summary.setProjectGroupId( task.getProjectGroupId() ); summary.setProjectGroupName( task.getProjectGroupName() ); summary.setScmRootId( task.getProjectScmRootId() ); summary.setScmRootAddress( task.getScmRootAddress() ); summary.setHashCode( task.getHashCode() ); summary.setQueueName( key ); prepareBuildQueues.add( summary ); } } } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } try { // queued builds Map<String, List<BuildProjectTask>> builds = getContinuum().getBuildsManager().getProjectsInBuildQueues(); Set<String> keySet = builds.keySet(); for ( String key : keySet ) { for ( BuildProjectTask task : builds.get( key ) ) { BuildProjectQueue queue = new BuildProjectQueue(); queue.setName( key ); queue.setTask( task ); buildsInQueue.add( queue ); } } } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } try { // current checkouts Map<String, CheckOutTask> currentCheckouts = getContinuum().getBuildsManager().getCurrentCheckouts(); Set<String> keySet = currentCheckouts.keySet(); for ( String key : keySet ) { CheckOutTask checkoutTask = currentCheckouts.get( key ); CheckoutQueue queue = new CheckoutQueue(); queue.setName( key ); queue.setTask( checkoutTask ); currentCheckoutTasks.add( queue ); } } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } try { // queued checkouts Map<String, List<CheckOutTask>> checkouts = getContinuum().getBuildsManager().getProjectsInCheckoutQueues(); Set<String> keySet = checkouts.keySet(); for ( String key : keySet ) { for ( CheckOutTask task : checkouts.get( key ) ) { CheckoutQueue queue = new CheckoutQueue(); queue.setName( key ); queue.setTask( task ); checkoutsInQueue.add( queue ); } } } catch ( BuildManagerException e ) { addActionError( e.getMessage() ); return ERROR; } } return SUCCESS; } public String remove() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getBuildsManager().removeProjectFromBuildQueue( projectId, buildDefinitionId, new BuildTrigger( trigger, "" ), projectName, projectGroupId ); Project project = getContinuum().getProject( projectId ); project.setState( project.getOldState() ); getContinuum().updateProject( project ); return SUCCESS; } public String removeBuildEntries() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getBuildsManager().removeProjectsFromBuildQueueWithHashcodes( listToIntArray( this.getSelectedBuildTaskHashCodes() ) ); return SUCCESS; } public String removeCheckoutEntries() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getBuildsManager().removeProjectsFromCheckoutQueueWithHashcodes( listToIntArray( this.getSelectedCheckOutTaskHashCodes() ) ); return SUCCESS; } public String removePrepareBuildEntry() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getBuildsManager().removeProjectFromPrepareBuildQueue( projectGroupId, scmRootId ); return SUCCESS; } public String removePrepareBuildEntries() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getBuildsManager().removeProjectsFromPrepareBuildQueueWithHashCodes( listToIntArray( this.selectedPrepareBuildTaskHashCodes ) ); return SUCCESS; } public String cancelDistributedBuild() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getDistributedBuildManager().cancelDistributedBuild( buildAgentUrl ); return SUCCESS; } public String removeDistributedPrepareBuildEntry() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getDistributedBuildManager().removeFromPrepareBuildQueue( buildAgentUrl, projectGroupId, scmRootId ); return SUCCESS; } public String removeDistributedPrepareBuildEntries() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getDistributedBuildManager().removeFromPrepareBuildQueue( this.getSelectedPrepareBuildTaskHashCodes() ); return SUCCESS; } public String removeDistributedBuildEntry() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getDistributedBuildManager().removeFromBuildQueue( buildAgentUrl, projectId, buildDefinitionId ); return SUCCESS; } public String removeDistributedBuildEntries() throws Exception { try { checkManageQueuesAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } catch ( AuthenticationRequiredException e ) { addActionError( e.getMessage() ); return REQUIRES_AUTHENTICATION; } getContinuum().getDistributedBuildManager().removeFromBuildQueue( this.getSelectedBuildTaskHashCodes() ); return SUCCESS; } private int[] listToIntArray( List<String> strings ) { if ( strings == null || strings.isEmpty() ) { return new int[0]; } int[] array = new int[0]; for ( String intString : strings ) { array = ArrayUtils.add( array, Integer.parseInt( intString ) ); } return array; } // ----------------------------------------------------- // security // ----------------------------------------------------- public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_VIEW_QUEUES, Resource.GLOBAL ); return bundle; } private boolean cancelCheckout( int projectId ) throws BuildManagerException { Map<String, CheckOutTask> tasks = getContinuum().getBuildsManager().getCurrentCheckouts(); if ( tasks != null ) { Set<String> keySet = tasks.keySet(); for ( String key : keySet ) { CheckOutTask task = tasks.get( key ); if ( task != null ) { if ( task.getProjectId() == projectId ) { logger.info( "Cancelling checkout for project " + projectId ); return getContinuum().getBuildsManager().cancelCheckout( projectId ); } else { logger.warn( "Current task is not for the given projectId (" + projectId + "): " + task.getProjectId() + "; not cancelling checkout" ); } } } } else { logger.warn( "No task running - not cancelling checkout" ); } return false; } public int getBuildDefinitionId() { return buildDefinitionId; } public void setBuildDefinitionId( int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public int getTrigger() { return trigger; } public void setTrigger( int trigger ) { this.trigger = trigger; } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public List<String> getSelectedBuildTaskHashCodes() { return selectedBuildTaskHashCodes; } public void setSelectedBuildTaskHashCodes( List<String> selectedBuildTaskHashCodes ) { this.selectedBuildTaskHashCodes = selectedBuildTaskHashCodes; } public List<String> getSelectedCheckOutTaskHashCodes() { return selectedCheckOutTaskHashCodes; } public void setSelectedCheckOutTaskHashCodes( List<String> selectedCheckOutTaskHashCodes ) { this.selectedCheckOutTaskHashCodes = selectedCheckOutTaskHashCodes; } public List<BuildProjectQueue> getCurrentBuildProjectTasks() { return currentBuildProjectTasks; } public void setCurrentBuildProjectTasks( List<BuildProjectQueue> currentBuildProjectTasks ) { this.currentBuildProjectTasks = currentBuildProjectTasks; } public List<CheckoutQueue> getCurrentCheckoutTasks() { return currentCheckoutTasks; } public void setCurrentCheckoutTasks( List<CheckoutQueue> currentCheckoutTasks ) { this.currentCheckoutTasks = currentCheckoutTasks; } public List<BuildProjectQueue> getBuildsInQueue() { return buildsInQueue; } public void setBuildsInQueue( List<BuildProjectQueue> buildsInQueue ) { this.buildsInQueue = buildsInQueue; } public List<CheckoutQueue> getCheckoutsInQueue() { return checkoutsInQueue; } public void setCheckoutsInQueue( List<CheckoutQueue> checkoutsInQueue ) { this.checkoutsInQueue = checkoutsInQueue; } public List<PrepareBuildSummary> getCurrentDistributedPrepareBuilds() { return currentDistributedPrepareBuilds; } public List<DistributedBuildSummary> getCurrentDistributedBuilds() { return currentDistributedBuilds; } public List<PrepareBuildSummary> getDistributedPrepareBuildQueues() { return distributedPrepareBuildQueues; } public List<DistributedBuildSummary> getDistributedBuildQueues() { return distributedBuildQueues; } public List<PrepareBuildSummary> getCurrentPrepareBuilds() { return currentPrepareBuilds; } public List<PrepareBuildSummary> getPrepareBuildQueues() { return prepareBuildQueues; } public String getBuildAgentUrl() { return buildAgentUrl; } public void setBuildAgentUrl( String buildAgentUrl ) { this.buildAgentUrl = buildAgentUrl; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public void setScmRootId( int scmRootId ) { this.scmRootId = scmRootId; } public void setSelectedPrepareBuildTaskHashCodes( List<String> selectedPrepareBuildTaskHashCodes ) { this.selectedPrepareBuildTaskHashCodes = selectedPrepareBuildTaskHashCodes; } public List<String> getSelectedPrepareBuildTaskHashCodes() { return selectedPrepareBuildTaskHashCodes; } }
5,535
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/ConfigurationAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.continuum.configuration.ContinuumConfigurationException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.configuration.ConfigurationStoringException; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.struts2.ServletActionContext; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.plexus.util.StringUtils; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import javax.servlet.http.HttpServletRequest; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "configuration", instantiationStrategy = "per-lookup" ) public class ConfigurationAction extends ContinuumActionSupport implements Preparable, SecureAction { private static final Logger log = LoggerFactory.getLogger( ConfigurationAction.class ); private String workingDirectory; private String buildOutputDirectory; private String deploymentRepositoryDirectory; private String baseUrl; private String releaseOutputDirectory; private int numberOfAllowedBuildsinParallel = 1; private boolean requireReleaseOutput; private boolean distributedBuildEnabled; private String sharedSecretPassword; public void prepare() { ConfigurationService configuration = getContinuum().getConfiguration(); File workingDirectoryFile = configuration.getWorkingDirectory(); if ( workingDirectoryFile != null ) { workingDirectory = workingDirectoryFile.getAbsolutePath(); validateDir( "workingDirectory", workingDirectoryFile ); } File buildOutputDirectoryFile = configuration.getBuildOutputDirectory(); if ( buildOutputDirectoryFile != null ) { buildOutputDirectory = buildOutputDirectoryFile.getAbsolutePath(); validateDir( "buildOutputDirectory", buildOutputDirectoryFile ); } File deploymentRepositoryDirectoryFile = configuration.getDeploymentRepositoryDirectory(); if ( deploymentRepositoryDirectoryFile != null ) { deploymentRepositoryDirectory = deploymentRepositoryDirectoryFile.getAbsolutePath(); validateDir( "deploymentRepositoryDirectory", deploymentRepositoryDirectoryFile ); } baseUrl = configuration.getUrl(); if ( StringUtils.isEmpty( baseUrl ) ) { HttpServletRequest request = ServletActionContext.getRequest(); baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); log.info( "baseUrl='" + baseUrl + "'" ); } File releaseOutputDirectoryFile = configuration.getReleaseOutputDirectory(); if ( releaseOutputDirectoryFile != null ) { releaseOutputDirectory = releaseOutputDirectoryFile.getAbsolutePath(); validateDir( "releaseOutputDirectory", releaseOutputDirectoryFile ); } numberOfAllowedBuildsinParallel = configuration.getNumberOfBuildsInParallel(); if ( numberOfAllowedBuildsinParallel == 0 ) { numberOfAllowedBuildsinParallel = 1; } String requireRelease = ServletActionContext.getRequest().getParameter( "requireReleaseOutput" ); setRequireReleaseOutput( Boolean.valueOf( requireRelease ) ); distributedBuildEnabled = configuration.isDistributedBuildEnabled(); sharedSecretPassword = configuration.getSharedSecretPassword(); } public String input() { if ( isRequireReleaseOutput() ) { addActionError( getText( "configuration.releaseOutputDirectory.required" ) ); } if ( numberOfAllowedBuildsinParallel <= 0 ) { addActionError( getText( "configuration.numberOfBuildsInParallel.invalid" ) ); } return INPUT; } public String save() throws ConfigurationStoringException { if ( numberOfAllowedBuildsinParallel <= 0 ) { addActionError( "Number of Allowed Builds in Parallel must be greater than zero." ); return INPUT; } ConfigurationService configuration = getContinuum().getConfiguration(); configuration.setWorkingDirectory( new File( workingDirectory ) ); configuration.setBuildOutputDirectory( new File( buildOutputDirectory ) ); configuration.setNumberOfBuildsInParallel( numberOfAllowedBuildsinParallel ); if ( StringUtils.isNotEmpty( deploymentRepositoryDirectory ) ) { configuration.setDeploymentRepositoryDirectory( new File( deploymentRepositoryDirectory ) ); } else { configuration.setDeploymentRepositoryDirectory( null ); } configuration.setUrl( baseUrl ); configuration.setInitialized( true ); if ( StringUtils.isNotEmpty( releaseOutputDirectory ) ) { configuration.setReleaseOutputDirectory( new File( releaseOutputDirectory ) ); } else if ( isRequireReleaseOutput() ) { addActionError( getText( "configuration.releaseOutputDirectory.required" ) ); return INPUT; } else { configuration.setReleaseOutputDirectory( null ); } configuration.setDistributedBuildEnabled( distributedBuildEnabled ); configuration.setSharedSecretPassword( sharedSecretPassword ); try { configuration.store(); } catch ( ContinuumConfigurationException cce ) { log.error( "failed to save configuration", cce ); addActionError( getText( "configuration.save.failed" ) ); return INPUT; } return SUCCESS; } private void validateDir( String fieldName, File dir ) { if ( dir.exists() ) { if ( !dir.isDirectory() ) { addFieldError( fieldName, getText( "configuration.dir.notdir" ) ); } if ( !dir.canWrite() ) { addFieldError( fieldName, getText( "configuration.dir.notwritable" ) ); } } } public String getWorkingDirectory() { return workingDirectory; } public void setWorkingDirectory( String workingDirectory ) { this.workingDirectory = workingDirectory; } public String getDeploymentRepositoryDirectory() { return deploymentRepositoryDirectory; } public void setDeploymentRepositoryDirectory( String deploymentRepositoryDirectory ) { this.deploymentRepositoryDirectory = deploymentRepositoryDirectory; } public String getBuildOutputDirectory() { return buildOutputDirectory; } public void setBuildOutputDirectory( String buildOutputDirectory ) { this.buildOutputDirectory = buildOutputDirectory; } public String getBaseUrl() { return baseUrl; } public void setBaseUrl( String baseUrl ) { this.baseUrl = baseUrl; } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_CONFIGURATION, Resource.GLOBAL ); return bundle; } public String getReleaseOutputDirectory() { return releaseOutputDirectory; } public void setReleaseOutputDirectory( String releaseOutputDirectory ) { this.releaseOutputDirectory = releaseOutputDirectory; } public boolean isRequireReleaseOutput() { return requireReleaseOutput; } public void setRequireReleaseOutput( boolean requireReleaseOutput ) { this.requireReleaseOutput = requireReleaseOutput; } public int getNumberOfAllowedBuildsinParallel() { return numberOfAllowedBuildsinParallel; } public void setNumberOfAllowedBuildsinParallel( int numberOfAllowedBuildsinParallel ) { this.numberOfAllowedBuildsinParallel = numberOfAllowedBuildsinParallel; } public boolean isDistributedBuildEnabled() { return distributedBuildEnabled; } public void setDistributedBuildEnabled( boolean distributedBuildEnabled ) { this.distributedBuildEnabled = distributedBuildEnabled; } public void setSharedSecretPassword( String sharedSecretPassword ) { this.sharedSecretPassword = sharedSecretPassword; } public String getSharedSecretPassword() { return sharedSecretPassword; } }
5,536
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/EditPomAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ModelDriven; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.maven.artifact.installer.ArtifactInstallationException; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; import org.apache.maven.continuum.execution.SettingsConfigurationException; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.model.Model; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.shared.app.company.CompanyPomHandler; import org.apache.maven.shared.app.configuration.CompanyPom; import org.apache.maven.shared.app.configuration.Configuration; import org.apache.maven.shared.app.configuration.MavenAppConfiguration; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.io.IOException; /** * @author <a href="mailto:brett@apache.org">Brett Porter</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "editPom", instantiationStrategy = "per-lookup" ) public class EditPomAction extends ContinuumActionSupport implements ModelDriven, SecureAction { @Requirement private MavenAppConfiguration appConfiguration; @Requirement private CompanyPomHandler companyPomHandler; private Model companyModel; private String organizationLogo; @Requirement private LocalRepositoryHelper helper; public String execute() throws IOException, ArtifactInstallationException, SettingsConfigurationException { if ( organizationLogo != null ) { companyModel.getProperties().setProperty( "organization.logo", organizationLogo ); } companyPomHandler.save( companyModel, helper.getLocalRepository() ); return SUCCESS; } public String input() { return INPUT; } public Object getModel() { return companyModel; } public void prepare() throws ProjectBuildingException, ArtifactMetadataRetrievalException, SettingsConfigurationException { Configuration configuration = appConfiguration.getConfiguration(); CompanyPom companyPom = configuration.getCompanyPom(); companyModel = companyPomHandler.getCompanyPomModel( companyPom, helper.getLocalRepository() ); if ( companyModel == null ) { companyModel = new Model(); companyModel.setModelVersion( "4.0.0" ); companyModel.setPackaging( "pom" ); if ( companyPom != null ) { companyModel.setGroupId( companyPom.getGroupId() ); companyModel.setArtifactId( companyPom.getArtifactId() ); } } organizationLogo = companyModel.getProperties().getProperty( "organization.logo" ); } public String getOrganizationLogo() { return organizationLogo; } public void setOrganizationLogo( String organizationLogo ) { this.organizationLogo = organizationLogo; } public Model getCompanyModel() { return companyModel; } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_CONFIGURATION, Resource.GLOBAL ); return bundle; } }
5,537
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/InstallationAction.java
package org.apache.maven.continuum.web.action.admin; import com.opensymphony.xwork2.Preparable; import org.apache.commons.lang.StringUtils; import org.apache.maven.continuum.installation.AlreadyExistsInstallationException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.profile.AlreadyExistsProfileException; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:olamy@codehaus.org">olamy</a> * @since 14 juin 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "installation", instantiationStrategy = "per-lookup" ) public class InstallationAction extends ContinuumConfirmAction implements Preparable, SecureAction { @Requirement( hint = "default" ) private InstallationService installationService; private List<Installation> installations; private Installation installation; private Map<String, String> typesLabels; private List<String> types; private boolean varNameUpdatable = false; private boolean automaticProfile; private boolean varNameDisplayable = false; private boolean displayTypes = true; private String installationType; private Map<String, String> installationTypes; private static final String TOOL_TYPE_KEY = "tool"; private boolean automaticProfileDisplayable = true; private boolean confirmed; // ----------------------------------------------------- // Webwork methods // ----------------------------------------------------- public String list() throws Exception { this.installations = installationService.getAllInstallations(); return SUCCESS; } public String edit() throws Exception { this.installation = installationService.getInstallation( installation.getInstallationId() ); if ( this.installation != null ) { this.configureUiFlags(); } this.automaticProfileDisplayable = false; return SUCCESS; } public String input() throws Exception { if ( InstallationService.ENVVAR_TYPE.equalsIgnoreCase( this.getInstallationType() ) ) { this.installation = new Installation(); this.installation.setType( InstallationService.ENVVAR_TYPE ); this.setDisplayTypes( false ); this.setVarNameUpdatable( true ); this.setVarNameDisplayable( true ); } else { this.setVarNameUpdatable( false ); this.setVarNameDisplayable( false ); } return INPUT; } public String save() throws Exception { if ( InstallationService.ENVVAR_TYPE.equalsIgnoreCase( this.getInstallationType() ) ) { this.installation.setType( InstallationService.ENVVAR_TYPE ); if ( StringUtils.isEmpty( installation.getVarName() ) ) { addFieldError( "installation.varName", getResourceBundle().getString( "installation.varName.required" ) ); return INPUT; } } if ( installation.getInstallationId() == 0 ) { try { installationService.add( installation, this.automaticProfile ); } catch ( AlreadyExistsInstallationException e ) { this.addActionError( getResourceBundle().getString( "installation.name.duplicate" ) ); return INPUT; } catch ( AlreadyExistsProfileException e ) { this.addActionError( getResourceBundle().getString( "profile.name.already.exists" ) ); return INPUT; } } else { this.configureUiFlags(); try { installationService.update( installation ); } catch ( AlreadyExistsInstallationException e ) { this.addActionError( getResourceBundle().getString( "installation.name.duplicate" ) ); return INPUT; } } return SUCCESS; } public String delete() throws Exception { if ( confirmed ) { Installation installationToDelete = installationService.getInstallation( installation.getInstallationId() ); installationService.delete( installationToDelete ); this.installations = installationService.getAllInstallations(); } else { return CONFIRM; } return SUCCESS; } public String listTypes() { this.installationTypes = new LinkedHashMap<String, String>(); ResourceBundle resourceBundle = getResourceBundle(); this.installationTypes.put( TOOL_TYPE_KEY, resourceBundle.getString( "installationTypeChoice.tool.label" ) ); this.installationTypes.put( InstallationService.ENVVAR_TYPE, resourceBundle.getString( "installationTypeChoice.envar.label" ) ); return SUCCESS; } // ----------------------------------------------------- // security // ----------------------------------------------------- public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_INSTALLATIONS, Resource.GLOBAL ); return bundle; } // ----------------------------------------------------- // utils // ----------------------------------------------------- private void configureUiFlags() { // we can update env var name only with env var type if ( !InstallationService.ENVVAR_TYPE.equals( this.installation.getType() ) ) { this.setDisplayTypes( true ); this.setVarNameUpdatable( false ); } else { this.setDisplayTypes( false ); this.setVarNameUpdatable( true ); this.setVarNameDisplayable( true ); } this.setInstallationType( this.getInstallation().getType() ); } // ----------------------------------------------------- // getter/setters // ----------------------------------------------------- public List<Installation> getInstallations() { return installations; } public void setInstallations( List<Installation> installations ) { this.installations = installations; } public Installation getInstallation() { return installation; } public void setInstallation( Installation installation ) { this.installation = installation; } public Map<String, String> getTypesLabels() { if ( this.typesLabels == null ) { this.typesLabels = new LinkedHashMap<String, String>(); ResourceBundle resourceBundle = getResourceBundle(); this.typesLabels.put( InstallationService.JDK_TYPE, resourceBundle.getString( "installation.jdk.type.label" ) ); this.typesLabels.put( InstallationService.MAVEN2_TYPE, resourceBundle.getString( "installation.maven2.type.label" ) ); this.typesLabels.put( InstallationService.MAVEN1_TYPE, resourceBundle.getString( "installation.maven1.type.label" ) ); this.typesLabels.put( InstallationService.ANT_TYPE, resourceBundle.getString( "installation.ant.type.label" ) ); // CONTINUUM-1430 //this.typesLabels.put( InstallationService.ENVVAR_TYPE, resourceBundle // .getString( "installation.envvar.type.label" ) ); } return typesLabels; } public void setTypesLabels( Map<String, String> typesLabels ) { this.typesLabels = typesLabels; } public boolean isVarNameUpdatable() { return varNameUpdatable; } public void setVarNameUpdatable( boolean varNameUpdatable ) { this.varNameUpdatable = varNameUpdatable; } public List<String> getTypes() { if ( this.types == null ) { this.types = new ArrayList<String>( 5 ); this.types.add( InstallationService.JDK_TYPE ); this.types.add( InstallationService.MAVEN2_TYPE ); this.types.add( InstallationService.MAVEN1_TYPE ); this.types.add( InstallationService.ANT_TYPE ); // CONTINUUM-1430 //this.types.add( InstallationService.ENVVAR_TYPE ); } return types; } public void setTypes( List<String> types ) { this.types = types; } public boolean isAutomaticProfile() { return automaticProfile; } public void setAutomaticProfile( boolean automaticProfile ) { this.automaticProfile = automaticProfile; } public Map<String, String> getInstallationTypes() { return installationTypes; } public void setInstallationTypes( Map<String, String> installationTypes ) { this.installationTypes = installationTypes; } public boolean isVarNameDisplayable() { return varNameDisplayable; } public void setVarNameDisplayable( boolean varNameDisplayable ) { this.varNameDisplayable = varNameDisplayable; } public boolean isDisplayTypes() { return displayTypes; } public void setDisplayTypes( boolean displayTypes ) { this.displayTypes = displayTypes; } public String getInstallationType() { return installationType; } public void setInstallationType( String installationType ) { this.installationType = installationType; } public boolean isAutomaticProfileDisplayable() { return automaticProfileDisplayable; } public void setAutomaticProfileDisplayable( boolean automaticProfileDisplayable ) { this.automaticProfileDisplayable = automaticProfileDisplayable; } public boolean isConfirmed() { return confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } }
5,538
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/BuildQueueAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildQueue; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.List; @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildQueueAction", instantiationStrategy = "per-lookup" ) public class BuildQueueAction extends ContinuumConfirmAction implements Preparable, SecureAction { private String name; private int size; private List<BuildQueue> buildQueueList; private BuildQueue buildQueue; private String message; private boolean confirmed; public void prepare() throws ContinuumException { this.buildQueueList = getContinuum().getAllBuildQueues(); } public String input() { return INPUT; } public String list() throws Exception { try { this.buildQueueList = getContinuum().getAllBuildQueues(); } catch ( ContinuumException e ) { addActionError( "Cannot get build queues from the database : " + e.getMessage() ); return ERROR; } return SUCCESS; } public String save() throws Exception { int allowedBuilds = getContinuum().getConfiguration().getNumberOfBuildsInParallel(); if ( allowedBuilds < ( this.buildQueueList.size() + 1 ) ) { addActionError( "You are only allowed " + allowedBuilds + " number of builds in parallel." ); return ERROR; } else { try { if ( !isDuplicate( name ) ) { BuildQueue buildQueue = new BuildQueue(); buildQueue.setName( name ); BuildQueue addedBuildQueue = getContinuum().addBuildQueue( buildQueue ); getContinuum().getBuildsManager().addOverallBuildQueue( addedBuildQueue ); AuditLog event = new AuditLog( "Build Queue id=" + addedBuildQueue.getId(), AuditLogConstants.ADD_BUILD_QUEUE ); event.setCategory( AuditLogConstants.BUILD_QUEUE ); event.setCurrentUser( getPrincipal() ); event.log(); } else { addActionError( "Build queue name already exists." ); return ERROR; } } catch ( ContinuumException e ) { addActionError( "Error adding build queue to database: " + e.getMessage() ); return ERROR; } catch ( BuildManagerException e ) { addActionError( "Error creating overall build queue: " + e.getMessage() ); return ERROR; } return SUCCESS; } } public String edit() throws Exception { try { BuildQueue buildQueueToBeEdited = getContinuum().getBuildQueue( this.buildQueue.getId() ); } catch ( ContinuumException e ) { addActionError( "Error retrieving build queue from the database : " + e.getMessage() ); return ERROR; } return SUCCESS; } public String delete() throws Exception { if ( confirmed ) { BuildQueue buildQueueToBeDeleted = getContinuum().getBuildQueue( this.buildQueue.getId() ); getContinuum().getBuildsManager().removeOverallBuildQueue( buildQueueToBeDeleted.getId() ); getContinuum().removeBuildQueue( buildQueueToBeDeleted ); this.buildQueueList = getContinuum().getAllBuildQueues(); AuditLog event = new AuditLog( "Build Queue id=" + buildQueue.getId(), AuditLogConstants.REMOVE_BUILD_QUEUE ); event.setCategory( AuditLogConstants.BUILD_QUEUE ); event.setCurrentUser( getPrincipal() ); event.log(); } else { return CONFIRM; } return SUCCESS; } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PARALLEL_BUILDS, Resource.GLOBAL ); return bundle; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public List<BuildQueue> getBuildQueueList() { return buildQueueList; } public void setBuildQueueList( List<BuildQueue> buildQueueList ) { this.buildQueueList = buildQueueList; } public int getSize() { return size; } public void setSize( int size ) { this.size = size; } public BuildQueue getBuildQueue() { return buildQueue; } public void setBuildQueue( BuildQueue buildQueue ) { this.buildQueue = buildQueue; } public String getMessage() { return message; } public void setMessage( String message ) { this.message = message; } private boolean isDuplicate( String queueName ) throws ContinuumException { boolean isExisting = false; List<BuildQueue> buildQueues = getContinuum().getAllBuildQueues(); for ( BuildQueue bq : buildQueues ) { if ( queueName.equals( bq.getName() ) ) { isExisting = true; break; } } return isExisting; } public boolean isConfirmed() { return confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } }
5,539
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/ConfigureAppearanceAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ModelDriven; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.continuum.execution.SettingsConfigurationException; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.component.AbstractFooterAction; import org.apache.maven.continuum.web.appareance.AppareanceConfiguration; import org.apache.maven.model.Model; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Repository; import org.apache.maven.settings.Settings; import org.apache.maven.shared.app.company.CompanyPomHandler; import org.apache.maven.shared.app.configuration.Configuration; import org.apache.maven.shared.app.configuration.MavenAppConfiguration; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.plexus.registry.RegistryException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author <a href="mailto:brett@apache.org">Brett Porter</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "configureAppearance", instantiationStrategy = "per-lookup" ) public class ConfigureAppearanceAction extends AbstractFooterAction implements ModelDriven, SecureAction { @Requirement private MavenAppConfiguration appConfiguration; /** * The configuration. */ private Configuration configuration; private Model companyModel; @Requirement private CompanyPomHandler companyPomHandler; @Requirement private LocalRepositoryHelper helper; @Requirement private MavenSettingsBuilder mavenSettingsBuilder; @Requirement private ArtifactRepositoryFactory artifactRepositoryFactory; @Requirement( hint = "default" ) private ArtifactRepositoryLayout layout; @Requirement private AppareanceConfiguration appareanceConfiguration; public String execute() throws IOException, RegistryException { appConfiguration.save( configuration ); return SUCCESS; } public String input() throws IOException, RegistryException { return INPUT; } public Object getModel() { return configuration; } public void prepare() throws ProjectBuildingException, ArtifactMetadataRetrievalException, SettingsConfigurationException, XmlPullParserException, IOException { Settings settings = mavenSettingsBuilder.buildSettings( false ); // Load extra repositories from active profiles List<String> profileIds = settings.getActiveProfiles(); List<Profile> profiles = settings.getProfiles(); List<ArtifactRepository> remoteRepositories = new ArrayList<ArtifactRepository>(); Map<String, Profile> profilesAsMap = settings.getProfilesAsMap(); if ( profileIds != null && !profileIds.isEmpty() ) { for ( String profileId : profileIds ) { Profile profile = profilesAsMap.get( profileId ); if ( profile != null ) { List<Repository> repos = profile.getRepositories(); if ( repos != null && !repos.isEmpty() ) { for ( Repository repo : repos ) { remoteRepositories.add( artifactRepositoryFactory.createArtifactRepository( repo.getId(), repo.getUrl(), layout, null, null ) ); } } } } } configuration = appConfiguration.getConfiguration(); companyModel = companyPomHandler.getCompanyPomModel( configuration.getCompanyPom(), helper.getLocalRepository(), remoteRepositories ); this.setFooter( appareanceConfiguration.getFooter() ); } public Model getCompanyModel() { return companyModel; } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_CONFIGURATION, Resource.GLOBAL ); return bundle; } }
5,540
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/admin/BuildDefinitionTemplateAction.java
package org.apache.maven.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.commons.lang.StringEscapeUtils; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.builddefinition.BuildDefinitionUpdatePolicyConstants; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.AbstractBuildDefinitionAction; import org.apache.maven.continuum.web.model.BuildDefinitionSummary; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 16 sept. 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildDefinitionTemplates", instantiationStrategy = "per-lookup" ) public class BuildDefinitionTemplateAction extends AbstractBuildDefinitionAction implements SecureAction, Preparable { private List<BuildDefinitionTemplate> templates; private BuildDefinitionTemplate buildDefinitionTemplate; private List<String> buildDefinitionTypes; private List<BuildDefinitionSummary> buildDefinitionSummaries; private BuildDefinition buildDefinition; private Collection<Schedule> schedules; private List<Profile> profiles; private List<String> selectedBuildDefinitionIds; private List<BuildDefinition> buildDefinitions; private Map<Integer, String> buildDefinitionUpdatePolicies; // ------------------------------------------------------- // Webwork Methods // ------------------------------------------------------- @Override public void prepare() throws Exception { super.prepare(); buildDefinitionTypes = new LinkedList<String>(); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR ); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR ); buildDefinitionTypes.add( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR ); this.setSchedules( getContinuum().getSchedules() ); this.setProfiles( getContinuum().getProfileService().getAllProfiles() ); this.setBuildDefinitions( getContinuum().getBuildDefinitionService().getAllTemplates() ); buildDefinitionUpdatePolicies = new HashMap<Integer, String>(); String text = getText( "buildDefinition.updatePolicy.always" ); buildDefinitionUpdatePolicies.put( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_ALWAYS, text ); text = getText( "buildDefinition.updatePolicy.never" ); buildDefinitionUpdatePolicies.put( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_NEVER, text ); text = getText( "buildDefinition.updatePolicy.newPom" ); buildDefinitionUpdatePolicies.put( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_ONLY_FOR_NEW_POM, text ); } public String input() throws Exception { return INPUT; } public String summary() throws Exception { this.templates = getContinuum().getBuildDefinitionService().getAllBuildDefinitionTemplate(); List<BuildDefinition> buildDefinitions = getContinuum().getBuildDefinitionService().getAllTemplates(); this.buildDefinitionSummaries = generateBuildDefinitionSummaries( buildDefinitions ); return SUCCESS; } public String edit() throws Exception { this.buildDefinitionTemplate = getContinuum().getBuildDefinitionService().getBuildDefinitionTemplate( this.buildDefinitionTemplate.getId() ); this.setBuildDefinitions( getContinuum().getBuildDefinitionService().getAllTemplates() ); this.selectedBuildDefinitionIds = new ArrayList<String>(); if ( this.buildDefinitionTemplate.getBuildDefinitions() != null ) { for ( BuildDefinition bd : (List<BuildDefinition>) buildDefinitionTemplate.getBuildDefinitions() ) { this.selectedBuildDefinitionIds.add( Integer.toString( bd.getId() ) ); } } List<BuildDefinition> nonUsedBuildDefinitions = new ArrayList<BuildDefinition>(); for ( BuildDefinition buildDefinition : getBuildDefinitions() ) { if ( !getSelectedBuildDefinitionIds().contains( Integer.toString( buildDefinition.getId() ) ) ) { nonUsedBuildDefinitions.add( buildDefinition ); } } this.setBuildDefinitions( nonUsedBuildDefinitions ); return SUCCESS; } public String save() throws Exception { List<BuildDefinition> selectedBuildDefinitions = getBuildDefinitionsFromSelectedBuildDefinitions(); BuildDefinitionTemplate result; AuditLog event = new AuditLog( buildDefinitionTemplate.getName(), AuditLogConstants.ADD_TEMPLATE ); event.setCategory( AuditLogConstants.TEMPLATE ); event.setCurrentUser( getPrincipal() ); if ( this.buildDefinitionTemplate.getId() > 0 ) { buildDefinitionTemplate.setBuildDefinitions( selectedBuildDefinitions ); result = this.getContinuum().getBuildDefinitionService().updateBuildDefinitionTemplate( buildDefinitionTemplate ); event.setAction( AuditLogConstants.MODIFY_TEMPLATE ); } else { buildDefinitionTemplate.setBuildDefinitions( selectedBuildDefinitions ); this.buildDefinitionTemplate = this.getContinuum().getBuildDefinitionService().addBuildDefinitionTemplate( buildDefinitionTemplate ); result = this.buildDefinitionTemplate; } if ( result == null ) { addActionError( getText( "buildDefintionTemplate.name.exists" ) ); return INPUT; } else { event.log(); } return SUCCESS; } public String delete() throws BuildDefinitionServiceException { if ( confirmed ) { buildDefinitionTemplate = getContinuum().getBuildDefinitionService().getBuildDefinitionTemplate( this.buildDefinitionTemplate.getId() ); AuditLog event = new AuditLog( buildDefinitionTemplate.getName(), AuditLogConstants.REMOVE_TEMPLATE ); event.setCategory( AuditLogConstants.TEMPLATE ); event.setCurrentUser( getPrincipal() ); event.log(); this.getContinuum().getBuildDefinitionService().removeBuildDefinitionTemplate( buildDefinitionTemplate ); } else { return CONFIRM; } return SUCCESS; } public List<BuildDefinition> getBuildDefinitionsFromSelectedBuildDefinitions() throws ContinuumException { if ( this.selectedBuildDefinitionIds == null ) { return Collections.EMPTY_LIST; } List<BuildDefinition> selectedBuildDefinitions = new ArrayList<BuildDefinition>(); for ( String selectedBuildDefinitionId : selectedBuildDefinitionIds ) { BuildDefinition buildDefinition = getContinuum().getBuildDefinition( Integer.parseInt( selectedBuildDefinitionId ) ); selectedBuildDefinitions.add( buildDefinition ); } return selectedBuildDefinitions; } // ----------------------------------------------------- // BuildDefinition // ----------------------------------------------------- public String editBuildDefinition() throws Exception { this.buildDefinition = getContinuum().getBuildDefinitionService().getBuildDefinition( this.buildDefinition.getId() ); return SUCCESS; } public String saveBuildDefinition() throws Exception { Schedule schedule = null; // need to escape xml to prevent xss attacks buildDefinition.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( buildDefinition.getDescription() ) ) ); if ( buildDefinition.getProfile() != null ) { Profile profile = getContinuum().getProfileService().getProfile( buildDefinition.getProfile().getId() ); if ( profile != null ) { buildDefinition.setProfile( profile ); } else { buildDefinition.setProfile( null ); } } if ( buildDefinition.getSchedule() != null ) { if ( buildDefinition.getSchedule().getId() > 0 ) { schedule = getContinuum().getSchedule( buildDefinition.getSchedule().getId() ); buildDefinition.setSchedule( schedule ); } } if ( this.buildDefinition.getId() > 0 ) { this.getContinuum().getBuildDefinitionService().updateBuildDefinition( buildDefinition ); } else { this.buildDefinition = this.getContinuum().getBuildDefinitionService().addBuildDefinition( buildDefinition ); } if ( schedule != null ) { getContinuum().activeBuildDefinitionSchedule( schedule ); } return SUCCESS; } public String deleteBuildDefinition() throws BuildDefinitionServiceException { if ( confirmed ) { if ( getContinuum().getBuildDefinitionService().isBuildDefinitionInUse( buildDefinition ) ) { addActionError( getText( "buildDefinition.used" ) ); return ERROR; } else { buildDefinition = getContinuum().getBuildDefinitionService().getBuildDefinition( this.buildDefinition.getId() ); this.getContinuum().getBuildDefinitionService().removeBuildDefinition( buildDefinition ); } } else { return CONFIRM; } return SUCCESS; } // ----------------------------------------------------- // security // ----------------------------------------------------- public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_BUILD_TEMPLATES, Resource.GLOBAL ); return bundle; } // ------------------------------------------------------- // Webwork setter/getter // ------------------------------------------------------- public BuildDefinitionTemplate getBuildDefinitionTemplate() { if ( buildDefinitionTemplate == null ) { this.buildDefinitionTemplate = new BuildDefinitionTemplate(); } return buildDefinitionTemplate; } public void setBuildDefinitionTemplate( BuildDefinitionTemplate buildDefinitionTemplate ) { this.buildDefinitionTemplate = buildDefinitionTemplate; } public List<String> getBuildDefinitionTypes() { return buildDefinitionTypes; } public void setBuildDefinitionTypes( List<String> buildDefinitionTypes ) { this.buildDefinitionTypes = buildDefinitionTypes; } public List<BuildDefinitionTemplate> getTemplates() { return templates; } public void setTemplates( List<BuildDefinitionTemplate> templates ) { this.templates = templates; } public List<BuildDefinitionSummary> getBuildDefinitionSummaries() { return buildDefinitionSummaries; } public void setBuildDefinitionSummaries( List<BuildDefinitionSummary> buildDefinitionSummaries ) { this.buildDefinitionSummaries = buildDefinitionSummaries; } public BuildDefinition getBuildDefinition() { if ( this.buildDefinition == null ) { this.buildDefinition = new BuildDefinition(); } return buildDefinition; } public void setBuildDefinition( BuildDefinition buildDefinition ) { this.buildDefinition = buildDefinition; } public List<Profile> getProfiles() { return profiles; } public void setProfiles( List<Profile> profiles ) { this.profiles = profiles; } public void setSchedules( Collection<Schedule> schedules ) { this.schedules = schedules; } public Collection<Schedule> getSchedules() { return schedules; } public List<BuildDefinition> getBuildDefinitions() { return buildDefinitions; } public void setBuildDefinitions( List<BuildDefinition> buildDefinitions ) { this.buildDefinitions = buildDefinitions; } public List<String> getSelectedBuildDefinitionIds() { return selectedBuildDefinitionIds == null ? Collections.EMPTY_LIST : selectedBuildDefinitionIds; } public void setSelectedBuildDefinitionIds( List<String> selectedBuildDefinitionIds ) { this.selectedBuildDefinitionIds = selectedBuildDefinitionIds; } public Map<Integer, String> getBuildDefinitionUpdatePolicies() { return buildDefinitionUpdatePolicies; } }
5,541
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/component/ContinuumTabAction.java
package org.apache.maven.continuum.web.action.component; import org.apache.maven.continuum.web.action.PlexusActionSupport; import org.codehaus.plexus.component.annotations.Component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "continuumTab", instantiationStrategy = "per-lookup" ) public class ContinuumTabAction extends PlexusActionSupport { protected String tabName; public String getTabName() { return tabName; } public void setTabName( String name ) { tabName = name; } }
5,542
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/component/BottomAction.java
package org.apache.maven.continuum.web.action.component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.component.annotations.Component; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 8 nov. 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "bottom", instantiationStrategy = "per-lookup" ) public class BottomAction extends AbstractFooterAction { public String execute() { return SUCCESS; } }
5,543
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/component/NotifierSummaryAction.java
/** * */ package org.apache.maven.continuum.web.action.component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.GenerateRecipentNotifier; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.model.NotifierSummary; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Component Action that prepares and provides Project Group Notifier and * Project Notifier summaries. * * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "notifierSummary", instantiationStrategy = "per-lookup" ) public class NotifierSummaryAction extends ContinuumActionSupport { private static final Logger logger = LoggerFactory.getLogger( NotifierSummaryAction.class ); /** * Identifier for the {@link ProjectGroup} for which the Notifier summary * needs to be prepared for. */ private int projectGroupId; /** * Identifier for the {@link Project} for which the Notifier summary needs * to be prepared for. */ private int projectId; /** * {@link ProjectGroup} instance to obtain the Notifier summary for. */ private ProjectGroup projectGroup; private List<NotifierSummary> projectGroupNotifierSummaries = new ArrayList<NotifierSummary>(); private List<NotifierSummary> projectNotifierSummaries = new ArrayList<NotifierSummary>(); private String projectGroupName = ""; /** * Prepare Notifier summary for a {@link Project}. * * @return */ public String summarizeForProject() { logger.debug( "Obtaining summary for Project Id: " + projectId ); try { checkViewProjectGroupAuthorization( getProjectGroupName() ); projectNotifierSummaries = summarizeForProject( projectId ); } catch ( ContinuumException e ) { logger.error( "Unable to prepare Notifier summaries for Project Id: " + projectId, e ); return ERROR; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return SUCCESS; } /** * Prepare Notifier summary for a {@link Project}. * * @param projectId The project id. * @return */ private List<NotifierSummary> summarizeForProject( int projectId ) throws ContinuumException { return gatherProjectNotifierSummaries( projectId ); } /** * Prepare Notifier summary for a {@link ProjectGroup}. * * @return */ public String summarizeForProjectGroup() { logger.debug( "Obtaining summary for ProjectGroup Id:" + projectGroupId ); try { checkViewProjectGroupAuthorization( getProjectGroupName() ); projectGroupNotifierSummaries = gatherGroupNotifierSummaries(); Collection<Project> projects = getContinuum().getProjectsInGroup( projectGroupId ); if ( projects != null ) { for ( Project project : projects ) { projectNotifierSummaries.addAll( summarizeForProject( project.getId() ) ); } } } catch ( ContinuumException e ) { logger.error( "Unable to prepare Notifier summaries for ProjectGroup Id: " + projectGroupId, e ); return ERROR; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return SUCCESS; } /** * Prepares and returns a list of Notifier summaries for the specified Project Id. * * @param projectId The project id. * @return List of {@link NotifierSummary} instance for the specified project. * @throws ContinuumException if there was an error obtaining * and preparing Notifier Summary list for the project */ private List<NotifierSummary> gatherProjectNotifierSummaries( int projectId ) throws ContinuumException { List<NotifierSummary> summaryList = new ArrayList<NotifierSummary>(); Project project = getContinuum().getProjectWithAllDetails( projectId ); for ( ProjectNotifier pn : (List<ProjectNotifier>) project.getNotifiers() ) { NotifierSummary ns = generateProjectNotifierSummary( pn, project ); summaryList.add( ns ); } return summaryList; } /** * Prepares and returns {@link ProjectGroup} summaries for the specified project group Id. * * @return * @throws ContinuumException if there was an error fetching the {@link ProjectGroup} for specified Id. */ private List<NotifierSummary> gatherGroupNotifierSummaries() throws ContinuumException { List<NotifierSummary> summaryList = new ArrayList<NotifierSummary>(); projectGroup = getContinuum().getProjectGroupWithBuildDetails( projectGroupId ); for ( ProjectNotifier pn : (List<ProjectNotifier>) projectGroup.getNotifiers() ) { NotifierSummary ns = generateGroupNotifierSummary( pn ); summaryList.add( ns ); } return summaryList; } /** * Prepares a {@link NotifierSummary} from a {@link ProjectNotifier} instance. * * @param notifier * @return */ private NotifierSummary generateProjectNotifierSummary( ProjectNotifier notifier, Project project ) { return generateNotifierSummary( notifier, projectGroupId, project ); } /** * Prepares a {@link NotifierSummary} from a {@link ProjectNotifier} instance. * * @param notifier * @return */ private NotifierSummary generateGroupNotifierSummary( ProjectNotifier notifier ) { return generateNotifierSummary( notifier, projectGroupId, null ); } /** * Prepares a {@link NotifierSummary} from a {@link ProjectNotifier} instance. * * @param notifier * @return */ private NotifierSummary generateNotifierSummary( ProjectNotifier notifier, int projectGroupId, Project project ) { NotifierSummary ns = new NotifierSummary(); ns.setId( notifier.getId() ); ns.setType( notifier.getType() ); ns.setProjectGroupId( projectGroupId ); if ( project != null ) { ns.setProjectId( project.getId() ); ns.setProjectName( project.getName() ); } if ( notifier.isFromProject() ) { ns.setFromProject( true ); } else { ns.setFromProject( false ); } String recipient = GenerateRecipentNotifier.generate( notifier ); ns.setRecipient( recipient ); // XXX: Hack - just for testing :) StringBuffer sb = new StringBuffer(); if ( notifier.isSendOnError() ) { sb.append( "Error" ); } if ( notifier.isSendOnFailure() ) { if ( sb.length() > 0 ) { sb.append( '/' ); } sb.append( "Failure" ); } if ( notifier.isSendOnSuccess() ) { if ( sb.length() > 0 ) { sb.append( '/' ); } sb.append( "Success" ); } if ( notifier.isSendOnWarning() ) { if ( sb.length() > 0 ) { sb.append( '/' ); } sb.append( "Warning" ); } if ( notifier.isSendOnScmFailure() ) { if ( sb.length() > 0 ) { sb.append( '/' ); } sb.append( "SCM Failure" ); } ns.setEvents( sb.toString() ); ns.setEnabled( notifier.isEnabled() ); return ns; } // property accessors /** * @return the projectGroupId */ public int getProjectGroupId() { return projectGroupId; } /** * @param projectGroupId the projectGroupId to set */ public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } /** * @return the projectId */ public int getProjectId() { return projectId; } /** * @param projectId the projectId to set */ public void setProjectId( int projectId ) { this.projectId = projectId; } /** * @return the projectGroup */ public ProjectGroup getProjectGroup() { return projectGroup; } /** * @param projectGroup the projectGroup to set */ public void setProjectGroup( ProjectGroup projectGroup ) { this.projectGroup = projectGroup; } /** * @return the projectGroupNotifierSummaries */ public List<NotifierSummary> getProjectGroupNotifierSummaries() { return projectGroupNotifierSummaries; } /** * @param projectGroupNotifierSummaries the projectGroupNotifierSummaries to set */ public void setProjectGroupNotifierSummaries( List<NotifierSummary> projectGroupNotifierSummaries ) { this.projectGroupNotifierSummaries = projectGroupNotifierSummaries; } /** * @return the projectNotifierSummaries */ public List<NotifierSummary> getProjectNotifierSummaries() { return projectNotifierSummaries; } /** * @param projectNotifierSummaries the projectNotifierSummaries to set */ public void setProjectNotifierSummaries( List<NotifierSummary> projectNotifierSummaries ) { this.projectNotifierSummaries = projectNotifierSummaries; } public String getProjectGroupName() throws ContinuumException { if ( projectGroupName == null || "".equals( projectGroupName ) ) { if ( projectGroupId != 0 ) { projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName(); } else { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } } return projectGroupName; } }
5,544
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/component/AbstractFooterAction.java
package org.apache.maven.continuum.web.action.component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.appareance.AppareanceConfiguration; import org.codehaus.plexus.component.annotations.Requirement; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 8 nov. 07 */ public abstract class AbstractFooterAction extends ContinuumActionSupport { private String footer; @Requirement private AppareanceConfiguration appareanceConfiguration; public String getContinuumFooter() { return appareanceConfiguration.getFooter(); } public String getFooter() { return footer; } public void setFooter( String footer ) { this.footer = footer; } }
5,545
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/component/CompanyInfoAction.java
package org.apache.maven.continuum.web.action.component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ActionSupport; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.maven.model.Model; import org.apache.maven.shared.app.company.CompanyPomHandler; import org.apache.maven.shared.app.configuration.MavenAppConfiguration; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; /** * Stores the company information for displaying on the page. */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "companyInfo", instantiationStrategy = "per-lookup" ) public class CompanyInfoAction extends ActionSupport { private String companyLogo; private String companyUrl; private String companyName; @Requirement private CompanyPomHandler handler; @Requirement private MavenAppConfiguration appConfiguration; @Requirement private LocalRepositoryHelper helper; public String execute() throws Exception { Model model = handler.getCompanyPomModel( appConfiguration.getConfiguration().getCompanyPom(), helper.getLocalRepository() ); if ( model != null ) { if ( model.getOrganization() != null ) { companyName = model.getOrganization().getName(); companyUrl = model.getOrganization().getUrl(); } companyLogo = model.getProperties().getProperty( "organization.logo" ); } return SUCCESS; } public String getCompanyLogo() { return companyLogo; } public String getCompanyUrl() { return companyUrl; } public String getCompanyName() { return companyName; } }
5,546
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/component/BuildDefinitionSummaryAction.java
package org.apache.maven.continuum.web.action.component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.action.AbstractBuildDefinitionAction; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.model.BuildDefinitionSummary; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * BuildDefinitionSummaryAction: * * @author Jesse McConnell <jmcconnell@apache.org> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildDefinitionSummary", instantiationStrategy = "per-lookup" ) public class BuildDefinitionSummaryAction extends AbstractBuildDefinitionAction { private static final Logger logger = LoggerFactory.getLogger( BuildDefinitionSummaryAction.class ); private int projectGroupId; private String projectGroupName; private int projectId; // Allow dont remove default group build definition in project list private int defaultGroupDefinitionId; private ProjectGroup projectGroup; private List<BuildDefinitionSummary> projectBuildDefinitionSummaries = new ArrayList<BuildDefinitionSummary>(); private List<BuildDefinitionSummary> groupBuildDefinitionSummaries = new ArrayList<BuildDefinitionSummary>(); private List<BuildDefinitionSummary> allBuildDefinitionSummaries = new ArrayList<BuildDefinitionSummary>(); //profileName public String summarizeForProject() { try { projectGroup = getContinuum().getProjectGroupByProjectId( projectId ); projectGroupId = projectGroup.getId(); projectGroupName = projectGroup.getName(); checkViewProjectGroupAuthorization( projectGroupName ); groupBuildDefinitionSummaries = gatherGroupBuildDefinitionSummaries( projectGroupId ); projectBuildDefinitionSummaries = gatherProjectBuildDefinitionSummaries( projectId, projectGroupId ); fixDefaultBuildDefinitions(); allBuildDefinitionSummaries.addAll( groupBuildDefinitionSummaries ); allBuildDefinitionSummaries.addAll( projectBuildDefinitionSummaries ); } catch ( ContinuumException e ) { logger.info( "unable to build summary" ); return ERROR; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return SUCCESS; } public String summarizeForGroup() { try { groupBuildDefinitionSummaries = gatherGroupBuildDefinitionSummaries( projectGroupId ); projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId ); checkViewProjectGroupAuthorization( projectGroup.getName() ); for ( Project project : projectGroup.getProjects() ) { projectBuildDefinitionSummaries.addAll( gatherProjectBuildDefinitionSummaries( project.getId(), projectGroupId ) ); } allBuildDefinitionSummaries.addAll( groupBuildDefinitionSummaries ); allBuildDefinitionSummaries.addAll( projectBuildDefinitionSummaries ); } catch ( ContinuumException e ) { logger.info( "unable to build summary" ); return ERROR; } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } return SUCCESS; } private void fixDefaultBuildDefinitions() { boolean containsDefaultBDForProject = false; for ( BuildDefinitionSummary bds : projectBuildDefinitionSummaries ) { if ( bds.isIsDefault() ) { containsDefaultBDForProject = true; } } for ( BuildDefinitionSummary bds : groupBuildDefinitionSummaries ) { if ( bds.isIsDefault() ) { defaultGroupDefinitionId = bds.getId(); } if ( containsDefaultBDForProject ) { bds.setIsDefault( false ); } } } private List<BuildDefinitionSummary> gatherProjectBuildDefinitionSummaries( int projectId, int projectGroupId ) throws ContinuumException { List<BuildDefinitionSummary> summaryList = new ArrayList<BuildDefinitionSummary>(); Project project = getContinuum().getProjectWithAllDetails( projectId ); for ( BuildDefinition bd : project.getBuildDefinitions() ) { BuildDefinitionSummary bds = generateBuildDefinitionSummary( bd ); bds.setFrom( "PROJECT" ); bds.setProjectId( project.getId() ); bds.setProjectName( project.getName() ); bds.setProjectGroupId( projectGroupId ); summaryList.add( bds ); } return summaryList; } private List<BuildDefinitionSummary> gatherGroupBuildDefinitionSummaries( int projectGroupId ) throws ContinuumException { List<BuildDefinitionSummary> summaryList = new ArrayList<BuildDefinitionSummary>(); projectGroup = getContinuum().getProjectGroupWithBuildDetails( projectGroupId ); for ( BuildDefinition bd : projectGroup.getBuildDefinitions() ) { BuildDefinitionSummary bds = generateBuildDefinitionSummary( bd ); bds.setFrom( "GROUP" ); bds.setProjectGroupId( projectGroup.getId() ); summaryList.add( bds ); } return summaryList; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getProjectGroupName() { return projectGroupName; } public void setProjectGroupName( String projectGroupName ) { this.projectGroupName = projectGroupName; } public List<BuildDefinitionSummary> getProjectBuildDefinitionSummaries() { return projectBuildDefinitionSummaries; } public void setProjectBuildDefinitionSummaries( List<BuildDefinitionSummary> projectBuildDefinitionSummaries ) { this.projectBuildDefinitionSummaries = projectBuildDefinitionSummaries; } public List<BuildDefinitionSummary> getGroupBuildDefinitionSummaries() { return groupBuildDefinitionSummaries; } public void setGroupBuildDefinitionSummaries( List<BuildDefinitionSummary> groupBuildDefinitionSummaries ) { this.groupBuildDefinitionSummaries = groupBuildDefinitionSummaries; } public List<BuildDefinitionSummary> getAllBuildDefinitionSummaries() { return allBuildDefinitionSummaries; } public void setAllBuildDefinitionSummaries( List<BuildDefinitionSummary> allBuildDefinitionSummaries ) { this.allBuildDefinitionSummaries = allBuildDefinitionSummaries; } public ProjectGroup getProjectGroup() { return projectGroup; } public void setProjectGroup( ProjectGroup projectGroup ) { this.projectGroup = projectGroup; } public int getDefaultGroupDefinitionId() { return defaultGroupDefinitionId; } }
5,547
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/StateCell.java
package org.apache.maven.continuum.web.view; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ActionContext; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.model.ProjectSummary; import org.apache.maven.continuum.web.util.StateGenerator; import org.apache.maven.continuum.web.util.UrlHelperFactory; import org.apache.struts2.ServletActionContext; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.redback.authorization.AuthorizationException; import org.codehaus.plexus.redback.system.SecuritySession; import org.codehaus.plexus.redback.system.SecuritySystem; import org.codehaus.plexus.redback.system.SecuritySystemConstants; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; import java.util.HashMap; /** * Used in Summary view * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @deprecated use of cells is discouraged due to lack of i18n and design in java code. * Use jsp:include instead. */ public class StateCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { String contextPath = tableModel.getContext().getContextPath(); if ( tableModel.getCurrentRowBean() instanceof ProjectSummary ) { ProjectSummary project = (ProjectSummary) tableModel.getCurrentRowBean(); String state = StateGenerator.generate( project.getState(), contextPath ); if ( project.getLatestBuildId() != -1 && project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.UPDATING && isAuthorized( project.getProjectGroupName() ) ) { return createActionLink( "buildResult", project, state ); } return state; } if ( tableModel.getCurrentRowBean() instanceof ProjectScmRoot ) { ProjectScmRoot projectScmRoot = (ProjectScmRoot) tableModel.getCurrentRowBean(); String state = StateGenerator.generate( projectScmRoot.getState(), contextPath ); if ( projectScmRoot.getState() != ContinuumProjectState.NEW && isAuthorized( projectScmRoot.getProjectGroup().getName() ) && projectScmRoot.getState() == ContinuumProjectState.ERROR ) { return createActionLink( "scmResult", projectScmRoot, state ); } return state; } return StateGenerator.generate( StateGenerator.UNKNOWN_STATE, contextPath ); } private static String createActionLink( String action, ProjectSummary project, String state ) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put( "projectId", project.getId() ); params.put( "projectName", project.getName() ); params.put( "buildId", project.getLatestBuildId() ); params.put( "projectGroupId", project.getProjectGroupId() ); String url = UrlHelperFactory.getInstance().buildUrl( "/" + action + ".action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); return "<a href=\"" + url + "\">" + state + "</a>"; } private static String createActionLink( String action, ProjectScmRoot scmRoot, String state ) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put( "projectGroupId", scmRoot.getProjectGroup().getId() ); params.put( "projectScmRootId", scmRoot.getId() ); String url = UrlHelperFactory.getInstance().buildUrl( "/" + action + ".action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); return "<a href=\"" + url + "\">" + state + "</a>"; } private boolean isAuthorized( String projectGroupName ) { // do the authz bit ActionContext context = ActionContext.getContext(); PlexusContainer container = (PlexusContainer) context.getApplication().get( PlexusConstants.PLEXUS_KEY ); SecuritySession securitySession = (SecuritySession) context.getSession().get( SecuritySystemConstants.SECURITY_SESSION_KEY ); try { SecuritySystem securitySystem = (SecuritySystem) container.lookup( SecuritySystem.ROLE ); if ( !securitySystem.isAuthorized( securitySession, ContinuumRoleConstants.CONTINUUM_VIEW_GROUP_OPERATION, projectGroupName ) ) { return false; } } catch ( ComponentLookupException cle ) { return false; } catch ( AuthorizationException ae ) { return false; } return true; } }
5,548
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/commons/DateCell.java
package org.apache.maven.continuum.web.view.commons; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.util.StringUtils; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; import org.extremecomponents.util.ExtremeUtils; import java.util.Calendar; import java.util.Locale; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @deprecated use of cells is discouraged due to lack of i18n and design in java code. * Use jsp:include instead. */ public class DateCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { String valueString = column.getPropertyValueAsString(); if ( !StringUtils.isEmpty( valueString ) && !"0".equals( valueString ) ) { Locale locale = tableModel.getLocale(); Object value = column.getPropertyValue(); if ( value instanceof Long ) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis( (Long) value ); value = cal.getTime(); } String format = column.getFormat(); if ( StringUtils.isEmpty( format ) ) { format = "MMM dd, yyyy hh:mm:ss aaa z"; } value = ExtremeUtils.formatDate( column.getParse(), format, value, locale ); column.setPropertyValue( value ); return value.toString(); } else { return "&nbsp;"; } } }
5,549
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/commons/EscapeHtmlCell.java
package org.apache.maven.continuum.web.view.commons; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringEscapeUtils; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; /** * A cell renderer that escapes a column's contents for safe display within an HTML page. */ public class EscapeHtmlCell extends DisplayCell { @Override protected String getCellValue( TableModel model, Column column ) { return StringEscapeUtils.escapeHtml( super.getCellValue( model, column ) ); } }
5,550
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/projectview/NotifierFromCell.java
package org.apache.maven.continuum.web.view.projectview; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectNotifier; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; /** * Used in Project view * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @deprecated use of cells is discouraged due to lack of i18n and design in java code. * Use jsp:include instead. */ public class NotifierFromCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { ProjectNotifier notifier = (ProjectNotifier) tableModel.getCurrentRowBean(); if ( notifier.isFromProject() ) { return "Project"; } else { return "User"; } } }
5,551
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/projectview/NotifierRecipientCell.java
package org.apache.maven.continuum.web.view.projectview; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.web.util.GenerateRecipentNotifier; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; /** * Used in Project view * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @deprecated use of cells is discouraged due to lack of i18n and design in java code. * Use jsp:include instead. */ public class NotifierRecipientCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { ProjectNotifier notifier = (ProjectNotifier) tableModel.getCurrentRowBean(); return GenerateRecipentNotifier.generate( notifier ); } }
5,552
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/projectview/NotifierEventCell.java
package org.apache.maven.continuum.web.view.projectview; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.ProjectNotifier; import org.codehaus.plexus.util.StringUtils; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; /** * Used in Project view * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @deprecated use of cells is discouraged due to lack of i18n and design in java code. * Use jsp:include instead. */ public class NotifierEventCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { ProjectNotifier notifier = (ProjectNotifier) tableModel.getCurrentRowBean(); String event = ""; if ( notifier.isSendOnSuccess() ) { event += "Success "; } if ( notifier.isSendOnFailure() ) { event += "Failures "; } if ( notifier.isSendOnWarning() ) { event += "Warnings "; } if ( notifier.isSendOnError() ) { event += "Errors"; } event = StringUtils.replace( event, " ", "/" ); return event; } }
5,553
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/buildresults/StateCell.java
package org.apache.maven.continuum.web.view.buildresults; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.web.util.StateGenerator; import org.apache.maven.continuum.web.util.UrlHelperFactory; import org.apache.struts2.ServletActionContext; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; import java.util.HashMap; /** * Used in BuildResults * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @deprecated use of cells is discouraged due to lack of i18n and design in java code. * Use jsp:include instead. */ public class StateCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { final Object rowObject = tableModel.getCurrentRowBean(); final Object colObject = column.getPropertyValue(); final String markedUpValue = iconifyResult( rowObject, colObject ); column.setPropertyValue( markedUpValue ); return markedUpValue; } public static String iconifyResult( Object rowObject, Object colObject ) { final int state = colObject instanceof Integer ? (Integer) colObject : -1; final String img = StateGenerator.generate( state, ServletActionContext.getRequest().getContextPath() ); return rowObject instanceof BuildResult ? createActionLink( "buildResult", (BuildResult) rowObject, img ) : img; } private static String createActionLink( String action, BuildResult result, String linkText ) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put( "projectId", result.getProject().getId() ); params.put( "buildId", result.getId() ); String url = UrlHelperFactory.getInstance().buildUrl( "/" + action + ".action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); return String.format( "<a href='%s''>%s</a>", url, linkText ); } }
5,554
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/jsp
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/jsp/ui/DateTag.java
package org.apache.maven.continuum.web.view.jsp.ui; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.TextProvider; import com.opensymphony.xwork2.util.ValueStack; import org.apache.struts2.views.jsp.ui.TextareaTag; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.jsp.JspException; /** * First attempt at creating a date tag for the webwork framework. The tag will * format a date by using either a specified format attribute, or by falling * back on to a globally defined 'webwork.date' property. * When nice="true" is specified, it will return a human readable string (in 2 hours, 3 minutes). * <p/> * From http://jira.opensymphony.com/browse/WW-805 * * @author <a href="mailto:philip.luppens@gmail.com">Philip Luppens</a> */ public class DateTag extends TextareaTag { /* * the name of our property which we will use if the optional format * parameter is not specified. */ public final static String DATETAG_PROPERTY = "webwork.date"; public final static String DATETAG_PROPERTY_PAST = "webwork.date.format.past"; public final static String DATETAG_DEFAULT_PAST = "{0} ago"; public final static String DATETAG_PROPERTY_FUTURE = "webwork.date.format.future"; public final static String DATETAG_DEFAULT_FUTURE = "in {0}"; public final static String DATETAG_PROPERTY_SECONDS = "webwork.date.format.seconds"; public final static String DATETAG_DEFAULT_SECONDS = "an instant"; public final static String DATETAG_PROPERTY_MINUTES = "webwork.date.format.minutes"; public final static String DATETAG_DEFAULT_MINUTES = "{0,choice,1#one minute|1<{0} minutes}"; public final static String DATETAG_PROPERTY_HOURS = "webwork.date.format.hours"; public final static String DATETAG_DEFAULT_HOURS = "{0,choice,1#one hour|1<{0} hours}{1,choice,0#|1#, one minute|1<, {1} minutes}"; public final static String DATETAG_PROPERTY_DAYS = "webwork.date.format.days"; public final static String DATETAG_DEFAULT_DAYS = "{0,choice,1#one day|1<{0} days}{1,choice,0#|1#, one hour|1<, {1} hours}"; public final static String DATETAG_PROPERTY_YEARS = "webwork.date.format.years"; public final static String DATETAG_DEFAULT_YEARS = "{0,choice,1#one year|1<{0} years}{1,choice,0#|1#, one day|1<, {1} days}"; //our optional format parameter private String format; private String nameAttr; private boolean nice; private Date date; private TextProvider tp; public int doEndTag() throws JspException { String actualName = findString( nameAttr ); String msg = null; ValueStack stack = getStack(); //find the name on the valueStack, and cast it to a date Object dateObj = stack.findValue( actualName ); if ( dateObj != null ) { if ( dateObj instanceof Date ) { date = (Date) dateObj; } else if ( dateObj instanceof Long ) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis( (Long) dateObj ); date = cal.getTime(); } else { throw new JspException( "Could not cast the requested object " + nameAttr + " to a java.util.Date" ); } } if ( date != null && date.getTime() > 0 ) { tp = findProviderInStack(); if ( tp == null ) { throw new JspException( "Could not find a TextProvider on the stack." ); } if ( nice ) { msg = formatTime( date ); } else { if ( format == null ) { String globalFormat; //if the format is not specified, fall back using the defined // property DATETAG_PROPERTY globalFormat = tp.getText( DATETAG_PROPERTY ); if ( globalFormat != null ) { msg = new SimpleDateFormat( globalFormat, ActionContext.getContext().getLocale() ).format( date ); } else { //fall back using the xwork date format ? } } else { msg = new SimpleDateFormat( format, ActionContext.getContext().getLocale() ).format( date ); } } } if ( msg != null ) { try { //if we used the id attribute, we will store the formatted date // in the valuestack, otherwise, we write it to the // outputstream. if ( getId() == null ) { pageContext.getOut().write( msg ); } else { stack.getContext().put( getId(), msg ); } } catch ( IOException e ) { throw new JspException( e ); } } return EVAL_PAGE; } private TextProvider findProviderInStack() { for ( Object o : getStack().getRoot() ) { if ( o instanceof TextProvider ) { return (TextProvider) o; } } return null; } public String formatTime( Date date ) { StringBuffer sb = new StringBuffer(); List<Object> args = new ArrayList<Object>(); long secs = ( new Date().getTime() - date.getTime() ) / 1000; long mins = secs / 60; int min = (int) mins % 60; long hours = mins / 60; int hour = (int) hours % 24; int days = (int) hours / 24; int day = days % 365; int years = days / 365; if ( Math.abs( secs ) < 60 ) { args.add( secs ); args.add( sb ); args.add( null ); sb.append( tp.getText( DATETAG_PROPERTY_SECONDS, DATETAG_DEFAULT_SECONDS, args ) ); } else if ( hours == 0 ) { args.add( (long) min ); args.add( sb ); args.add( null ); sb.append( tp.getText( DATETAG_PROPERTY_MINUTES, DATETAG_DEFAULT_MINUTES, args ) ); } else if ( days == 0 ) { args.add( (long) hour ); args.add( (long) min ); args.add( sb ); args.add( null ); sb.append( tp.getText( DATETAG_PROPERTY_HOURS, DATETAG_DEFAULT_HOURS, args ) ); } else if ( years == 0 ) { args.add( (long) days ); args.add( (long) hour ); args.add( sb ); args.add( null ); sb.append( tp.getText( DATETAG_PROPERTY_DAYS, DATETAG_DEFAULT_DAYS, args ) ); } else { args.add( new Object[]{(long) years} ); args.add( new Object[]{(long) day} ); args.add( sb ); args.add( null ); sb.append( tp.getText( DATETAG_PROPERTY_YEARS, DATETAG_DEFAULT_YEARS, args ) ); } args.clear(); args.add( sb.toString() ); if ( date.before( new Date() ) ) { //looks like this date is passed return tp.getText( DATETAG_PROPERTY_PAST, DATETAG_DEFAULT_PAST, args ); } else { return tp.getText( DATETAG_PROPERTY_FUTURE, DATETAG_DEFAULT_FUTURE, args ); } } public void setName( String name ) { this.nameAttr = name; } public String getFormat() { return format; } public void setFormat( String format ) { this.format = format; } public boolean isNice() { return nice; } public void setNice( boolean nice ) { this.nice = nice; } }
5,555
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/jsp
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/jsp/ui/IfBuildTypeEnabledTag.java
package org.apache.maven.continuum.web.view.jsp.ui; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.Continuum; import org.codehaus.plexus.spring.PlexusToSpringUtils; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.jstl.core.ConditionalTagSupport; /** * ifBuildTypeEnabledTag: * * @author Jan Ancajas <jansquared@gmail.com> */ public class IfBuildTypeEnabledTag extends ConditionalTagSupport { private Continuum continuum; private String buildType; public static final String DISTRIBUTED = "distributed"; protected boolean condition() throws JspTagException { ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext( pageContext.getServletContext() ); this.setContinuum( (Continuum) applicationContext.getBean( PlexusToSpringUtils.buildSpringId( Continuum.ROLE, "default" ) ) ); if ( continuum == null ) { throw new JspTagException( "cannot lookup component: " + Continuum.ROLE ); } if ( DISTRIBUTED.equals( buildType ) ) { return continuum.getConfiguration().isDistributedBuildEnabled(); } // left out 'parallel' buildType checking for cyclomatic complexity's sake :) return !continuum.getConfiguration().isDistributedBuildEnabled(); } public String getBuildType() { return buildType; } public void setBuildType( String buildType ) { this.buildType = buildType; } public Continuum getContinuum() { return continuum; } public void setContinuum( Continuum continuum ) { this.continuum = continuum; } }
5,556
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/exception/AuthorizationRequiredException.java
package org.apache.maven.continuum.web.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Thrown when authorization check fails * * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a> */ public class AuthorizationRequiredException extends Exception { public AuthorizationRequiredException( String string ) { super( string ); } public AuthorizationRequiredException( String string, Throwable throwable ) { super( string, throwable ); } }
5,557
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/exception/ContinuumActionException.java
package org.apache.maven.continuum.web.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * ContinuumActionException: * * @author Jesse McConnell <jmcconnell@apache.org> */ public class ContinuumActionException extends Exception { public ContinuumActionException( String string ) { super( string ); } public ContinuumActionException( String string, Throwable throwable ) { super( string, throwable ); } }
5,558
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/exception/AuthenticationRequiredException.java
package org.apache.maven.continuum.web.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Used when authentication is checked during authorization * checks within action classes * * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a> */ public class AuthenticationRequiredException extends Exception { public AuthenticationRequiredException( String string ) { super( string ); } public AuthenticationRequiredException( String string, Throwable throwable ) { super( string, throwable ); } }
5,559
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/maven/continuum/web/interceptor/ForceContinuumConfigurationInterceptor.java
package org.apache.maven.continuum.web.interceptor; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.configuration.ConfigurationService; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; /** * ForceContinuumConfigurationInterceptor: * * @author: Jesse McConnell <jmcconnell@apache.org> */ @Component( role = com.opensymphony.xwork2.interceptor.Interceptor.class, hint = "forceContinuumConfigurationInterceptor" ) public class ForceContinuumConfigurationInterceptor implements Interceptor { private static boolean checked = false; @Requirement private Continuum continuum; public void destroy() { // no-op } public void init() { } /** * 1) check to see if this interceptor has been successfully executed * 2) check if the configuration service is initialized * 3) load the configuration and see if that is initialized (addresses restore on empty db) * 4) force the configuration screen * * @param invocation * @return * @throws Exception */ public String intercept( ActionInvocation invocation ) throws Exception { if ( checked ) { return invocation.invoke(); } ConfigurationService configuration = continuum.getConfiguration(); if ( configuration.isInitialized() ) { checked = true; return invocation.invoke(); } configuration.reload(); if ( configuration.isInitialized() ) { checked = true; return invocation.invoke(); } else { return "continuum-configuration-required"; } } }
5,560
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/util/AuditLog.java
package org.apache.continuum.web.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; /** * @author Jevica Arianne B. Zurbano * @since 17 apr 09 */ public class AuditLog { private Logger logger = LoggerFactory.getLogger( AuditLog.class.getName() ); private String action; private String category; private String resource; private String currentUser; public AuditLog( String action ) { this.action = action; } public AuditLog( String resource, String action ) { this.action = action; this.resource = resource; } public void setCurrentUser( String currentUser ) { this.currentUser = currentUser; } public String getCurrentUser() { return currentUser; } public void setResource( String resource ) { this.resource = resource; } public String getResource() { return resource; } public void setCategory( String category ) { this.category = category; } public String getCategory() { return category; } public void setAction( String action ) { this.action = action; } public String getAction() { return action; } public void log() { if ( currentUser != null ) { MDC.put( "security.currentUser", currentUser ); } if ( resource != null ) { if ( category != null ) { logger.info( category + " " + resource + " - " + action ); } else { logger.info( resource + " - " + action ); } } } }
5,561
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/util/GenerateRecipentNotifier.java
package org.apache.continuum.web.util; import org.apache.commons.lang.StringEscapeUtils; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.codehaus.plexus.util.StringUtils; import java.util.Map; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author José Morales Martínez */ public final class GenerateRecipentNotifier { private GenerateRecipentNotifier() { } @SuppressWarnings( "unchecked" ) public static String generate( ProjectNotifier notifier ) { Map<String, String> configuration = notifier.getConfiguration(); String recipent = "unknown"; if ( ( "mail".equals( notifier.getType() ) ) || ( "msn".equals( notifier.getType() ) ) || ( "jabber".equals( notifier.getType() ) ) ) { if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ) ) ) { recipent = configuration.get( AbstractContinuumNotifier.ADDRESS_FIELD ); } if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.COMMITTER_FIELD ) ) ) { if ( Boolean.parseBoolean( configuration.get( AbstractContinuumNotifier.COMMITTER_FIELD ) ) ) { if ( "unknown".equals( recipent ) ) { recipent = "latest committers"; } else { recipent += ", " + "latest committers"; } } } if ( StringUtils.isNotEmpty( configuration.get( AbstractContinuumNotifier.DEVELOPER_FIELD ) ) ) { if ( Boolean.parseBoolean( configuration.get( AbstractContinuumNotifier.DEVELOPER_FIELD ) ) ) { if ( "unknown".equals( recipent ) ) { recipent = "project developers"; } else { recipent += ", " + "project developers"; } } } } if ( "irc".equals( notifier.getType() ) ) { recipent = configuration.get( "host" ); if ( configuration.get( "port" ) != null ) { recipent = recipent + ":" + configuration.get( "port" ); } recipent = recipent + ":" + configuration.get( "channel" ); } if ( "wagon".equals( notifier.getType() ) ) { recipent = configuration.get( "url" ); } // escape the characters, it may contain characters possible for an XSS attack return StringEscapeUtils.escapeXml( recipent ); } }
5,562
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/util/AuditLogConstants.java
package org.apache.continuum.web.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author Jevica Arianne B. Zurbano * @since 09 apr 09 */ public class AuditLogConstants { public static final String PROJECT = "PROJECT"; public static final String SCHEDULE = "BUILD_SCHEDULE"; public static final String TEMPLATE = "BUILD_TEMPLATE"; public static final String BUILD_DEFINITION = "BUILD_DEFINITION"; public static final String PROJECT_GROUP = "PROJECT_GROUP"; public static final String BUILD_RESULT = "BUILD_RESULT"; public static final String BUILD_QUEUE = "BUILD_QUEUE"; public static final String BUILD_AGENT = "BUILD_AGENT"; public static final String LOCAL_REPOSITORY = "LOCAL_REPOSITORY"; public static final String DIRECTORY = "DIRECTORY"; // events public static final String FORCE_BUILD = "Forced Project Build"; public static final String CANCEL_BUILD = "Cancelled Project Build"; public static final String CI_BUILD = "Scheduled Project Build"; public static final String PREPARE_RELEASE = "Prepare Project Release"; public static final String PERFORM_RELEASE = "Perform Project Release"; public static final String ROLLBACK_RELEASE = "Rollback Project Release"; public static final String ADD_M2_PROJECT = "Added M2 Project"; public static final String ADD_M2_PROJECT_FAILED = "Failed Adding M2 Project"; public static final String ADD_M1_PROJECT = "Added M1 Project"; public static final String ADD_M1_PROJECT_FAILED = "Failed Adding M1 Project"; public static final String ADD_PROJECT = "Added Project"; public static final String MODIFY_PROJECT = "Modified Project"; public static final String REMOVE_PROJECT = "Removed Project"; public static final String ADD_PROJECT_GROUP = "Added Project Group"; public static final String MODIFY_PROJECT_GROUP = "Modified Project Group"; public static final String REMOVE_PROJECT_GROUP = "Removed Project Group"; public static final String MODIFY_SCHEDULE = "Modified Build Schedule"; public static final String ADD_SCHEDULE = "Added Build Schedule"; public static final String REMOVE_SCHEDULE = "Removed Build Schedule"; public static final String ADD_GOAL = "Added Build Definition"; public static final String MODIFY_GOAL = "Modified Build Definition"; public static final String REMOVE_GOAL = "Removed Build Definition"; public static final String ADD_TEMPLATE = "Added Build Definition Template"; public static final String MODIFY_TEMPLATE = "Modified Build Definition Template"; public static final String REMOVE_TEMPLATE = "Removed Build Definition Template"; public static final String REMOVE_BUILD_RESULT = "Removed Build Result"; public static final String ADD_BUILD_QUEUE = "Added Build Queue"; public static final String REMOVE_BUILD_QUEUE = "Removed Build Queue"; public static final String PURGE_LOCAL_REPOSITORY = "Purged Local Repository"; public static final String PURGE_DIRECTORY_RELEASES = "Purged Releases Directory"; public static final String PURGE_DIRECTORY_BUILDOUTPUT = "Purged Build Output Directory"; public static final String ADD_BUILD_AGENT = "Added Build Agent"; public static final String ADD_BUILD_AGENT_GROUP = "Added Build Agent Group"; public static final String MODIFY_BUILD_AGENT = "Modified Build Agent"; public static final String MODIFY_BUILD_AGENT_GROUP = "Modified Build Agent Group"; public static final String REMOVE_BUILD_AGENT = "Removed Build Agent"; public static final String REMOVE_BUILD_AGENT_GROUP = "Removed Build Agent Group"; }
5,563
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/util/FixedBufferAppender.java
package org.apache.continuum.web.util; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.util.Collection; import java.util.Collections; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class FixedBufferAppender extends AppenderSkeleton { private final Queue<String> lines = new ConcurrentLinkedQueue<String>(); private int linesBuffered = 120; private int queued = 0; @Override protected void append( LoggingEvent event ) { String formattedLine = layout.format( event ); // Add formatted line (may contain throwable if layout handles) lines.add( formattedLine ); queued++; // Add throwable information if layout doesn't handle ThrowableInformation throwInfo = event.getThrowableInformation(); if ( throwInfo != null && layout.ignoresThrowable() ) { for ( String traceLine : throwInfo.getThrowableStrRep() ) { lines.add( String.format( "%s%n", traceLine ) ); queued++; } } // Shrink the queue back to the desired buffer size (temporarily gets larger) while ( queued > linesBuffered ) { lines.remove(); queued--; } } @Override public boolean requiresLayout() { return true; } @Override public void close() { lines.clear(); queued = 0; } public void setLinesBuffered( int linesBuffered ) { this.linesBuffered = linesBuffered; } public Collection<String> getLines() { return Collections.unmodifiableCollection( lines ); } }
5,564
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/integration/Struts2PlexusInSpringObjectFactory.java
package org.apache.continuum.web.integration; /* ~ 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. */ import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.Result; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.interceptor.Interceptor; import com.opensymphony.xwork2.validator.Validator; import org.apache.struts2.StrutsConstants; import org.apache.struts2.spring.StrutsSpringObjectFactory; import org.codehaus.plexus.spring.PlexusToSpringUtils; import javax.servlet.ServletContext; import java.util.Map; public class Struts2PlexusInSpringObjectFactory extends StrutsSpringObjectFactory { @Inject public Struts2PlexusInSpringObjectFactory( @Inject(value=StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE,required=false) String autoWire, @Inject(value=StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE_ALWAYS_RESPECT,required=false) String alwaysAutoWire, @Inject(value=StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_USE_CLASS_CACHE,required=false) String useClassCacheStr, @Inject(value=StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_ENABLE_AOP_SUPPORT,required=false) String enableAopSupport, @Inject ServletContext servletContext, @Inject(StrutsConstants.STRUTS_DEVMODE) String devMode, @Inject Container container) { super(autoWire, alwaysAutoWire, useClassCacheStr, enableAopSupport, servletContext, devMode, container); } /** * {@inheritDoc} * * @see com.opensymphony.xwork2.spring.SpringObjectFactory#buildBean(java.lang.String, java.util.Map) */ @Override public Object buildBean( String name, Map map ) throws Exception { String id = PlexusToSpringUtils.buildSpringId(Action.class, name); if ( appContext.containsBean( id ) ) { return super.buildBean( id, map ); } id = PlexusToSpringUtils.buildSpringId( Result.class, name ); if ( appContext.containsBean( id ) ) { return super.buildBean( id, map ); } id = PlexusToSpringUtils.buildSpringId( Interceptor.class, name ); if ( appContext.containsBean( id ) ) { return super.buildBean( id, map ); } id = PlexusToSpringUtils.buildSpringId( Validator.class, name ); if ( appContext.containsBean( id ) ) { return super.buildBean( id, map ); } return super.buildBean( name, map ); } public Validator buildValidator( String className, Map params, Map extraContext ) throws Exception { String id = PlexusToSpringUtils.buildSpringId( Validator.class, className ); if ( appContext.containsBean( id ) ) { return (Validator) appContext.getBean( id ); } return super.buildValidator( className, params, extraContext ); } @Override public Class getClassInstance( String className ) throws ClassNotFoundException { String id = PlexusToSpringUtils.buildSpringId( Action.class, className ); if ( appContext.containsBean( id ) ) { return appContext.getType( id ); } id = PlexusToSpringUtils.buildSpringId( Result.class, className ); if ( appContext.containsBean( id ) ) { return appContext.getType( id ); } id = PlexusToSpringUtils.buildSpringId( Interceptor.class, className ); if ( appContext.containsBean( id ) ) { return appContext.getType( id ); } id = PlexusToSpringUtils.buildSpringId( Validator.class, className ); if ( appContext.containsBean( id ) ) { return appContext.getType( id ); } return super.getClassInstance( className ); } }
5,565
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/AbstractReleaseAction.java
package org.apache.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.codehaus.plexus.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class AbstractReleaseAction extends ContinuumActionSupport { protected Map<String, String> getEnvironments( Profile profile, String defaultBuildagent ) { if ( profile == null ) { if ( defaultBuildagent != null ) { return Collections.singletonMap( DistributedReleaseUtil.KEY_BUILD_AGENT_URL, defaultBuildagent ); } else { return Collections.emptyMap(); } } Map<String, String> envVars = new HashMap<String, String>(); if ( defaultBuildagent != null && defaultBuildagent.length() > 0 ) { // get buildagent to be used from the buildagent group for distributed builds setup BuildAgentGroupConfiguration group = getContinuum().getConfiguration().getBuildAgentGroup( profile.getBuildAgentGroup() ); if ( group != null ) { List<BuildAgentConfiguration> agents = group.getBuildAgents(); if ( agents != null ) { if ( isDefaultBuildAgentEnabledInGroup( defaultBuildagent, agents ) ) { envVars.put( DistributedReleaseUtil.KEY_BUILD_AGENT_URL, defaultBuildagent ); } else { for ( BuildAgentConfiguration agent : agents ) { if ( agent.isEnabled() == true ) { envVars.put( DistributedReleaseUtil.KEY_BUILD_AGENT_URL, agent.getUrl() ); break; } } } } } } String javaHome = getJavaHomeValue( profile ); if ( !StringUtils.isEmpty( javaHome ) ) { envVars.put( getContinuum().getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), javaHome ); } Installation builder = profile.getBuilder(); if ( builder != null ) { envVars.put( getContinuum().getInstallationService().getEnvVar( InstallationService.MAVEN2_TYPE ), builder.getVarValue() ); } List<Installation> installations = profile.getEnvironmentVariables(); for ( Installation installation : installations ) { envVars.put( installation.getVarName(), installation.getVarValue() ); } return envVars; } private boolean isDefaultBuildAgentEnabledInGroup( String defaultBuildagent, List<BuildAgentConfiguration> agents ) { boolean isInGroup = false; for ( BuildAgentConfiguration agent : agents ) { if ( agent.isEnabled() == true ) { if ( defaultBuildagent.equals( agent.getUrl() ) ) { isInGroup = true; break; } } } return isInGroup; } private String getJavaHomeValue( Profile profile ) { Installation jdk = profile.getJdk(); if ( jdk == null ) { return null; } return jdk.getVarValue(); } }
5,566
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/ReleaseResultAction.java
package org.apache.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringEscapeUtils; import org.apache.continuum.model.release.ContinuumReleaseResult; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.shared.release.ReleaseResult; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.List; /** * @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "releaseResult", instantiationStrategy = "per-lookup" ) public class ReleaseResultAction extends ContinuumConfirmAction { private static final Logger logger = LoggerFactory.getLogger( ReleaseResultAction.class ); @Requirement private FileSystemManager fsManager; private int projectGroupId; private int releaseResultId; private List<ContinuumReleaseResult> releaseResults; private List<String> selectedReleaseResults; private ProjectGroup projectGroup; private ReleaseResult result; private boolean confirmed; private String projectName; private String releaseGoal; private String username; public String list() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } releaseResults = getContinuum().getContinuumReleaseResultsByProjectGroup( projectGroupId ); return SUCCESS; } public String remove() throws ContinuumException { try { checkModifyProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } if ( confirmed ) { if ( selectedReleaseResults != null && !selectedReleaseResults.isEmpty() ) { for ( String id : selectedReleaseResults ) { int resultId = Integer.parseInt( id ); try { logger.info( "Removing ContinuumReleaseResult with id=" + resultId ); getContinuum().removeContinuumReleaseResult( resultId ); } catch ( ContinuumException e ) { logger.error( "Error removing ContinuumReleaseResult with id=" + resultId ); addActionError( getText( "Unable to remove ContinuumReleaseResult with id=" + resultId ) ); } } } return SUCCESS; } return CONFIRM; } public String viewResult() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } ContinuumReleaseResult releaseResult = getContinuum().getContinuumReleaseResult( releaseResultId ); result = new ReleaseResult(); result.setStartTime( releaseResult.getStartTime() ); result.setEndTime( releaseResult.getEndTime() ); result.setResultCode( releaseResult.getResultCode() ); releaseGoal = releaseResult.getReleaseGoal(); projectName = releaseResult.getProject().getName(); username = releaseResult.getUsername(); try { File releaseOutputFile = getContinuum().getConfiguration().getReleaseOutputFile( projectGroupId, "releases-" + releaseResult.getStartTime() ); if ( releaseOutputFile.exists() ) { String str = StringEscapeUtils.escapeHtml( fsManager.fileContents( releaseOutputFile ) ); result.appendOutput( str ); } } catch ( ConfigurationException e ) { //getLogger().error( "" ); } catch ( IOException e ) { //getLogger().error( "" ); } return SUCCESS; } public String getProjectGroupName() throws ContinuumException { return getProjectGroup( projectGroupId ).getName(); } public ProjectGroup getProjectGroup( int projectGroupId ) throws ContinuumException { if ( projectGroup == null ) { projectGroup = getContinuum().getProjectGroup( projectGroupId ); } else { if ( projectGroup.getId() != projectGroupId ) { projectGroup = getContinuum().getProjectGroup( projectGroupId ); } } return projectGroup; } public ProjectGroup getProjectGroup() { return projectGroup; } public void setProjectGroup( ProjectGroup projectGroup ) { this.projectGroup = projectGroup; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getReleaseResultId() { return releaseResultId; } public void setReleaseResultId( int releaseResultId ) { this.releaseResultId = releaseResultId; } public List<ContinuumReleaseResult> getReleaseResults() { return releaseResults; } public void setReleaseResults( List<ContinuumReleaseResult> releaseResults ) { this.releaseResults = releaseResults; } public List<String> getSelectedReleaseResults() { return selectedReleaseResults; } public void setSelectedReleaseResults( List<String> selectedReleaseResults ) { this.selectedReleaseResults = selectedReleaseResults; } public ReleaseResult getResult() { return result; } public void setResult( ReleaseResult result ) { this.result = result; } public boolean isConfirmed() { return confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public String getReleaseGoal() { return releaseGoal; } public void setReleaseGoal( String releaseGoal ) { this.releaseGoal = releaseGoal; } public void setUsername( String username ) { this.username = username; } public String getUsername() { return username; } }
5,567
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/ViewBuildsReportAction.java
package org.apache.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateUtils; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.struts2.interceptor.ServletResponseAware; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Writer; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Component( role = com.opensymphony.xwork2.Action.class, hint = "projectBuildsReport", instantiationStrategy = "per-lookup" ) public class ViewBuildsReportAction extends ContinuumActionSupport implements ServletResponseAware { private static final Logger log = LoggerFactory.getLogger( ViewBuildsReportAction.class ); private static final int MAX_BROWSE_SIZE = 500; private static final int EXPORT_BATCH_SIZE = 4000; private static final int MAX_EXPORT_SIZE = 100000; private static final String[] datePatterns = new String[] { "MM/dd/yy", "MM/dd/yyyy", "MMMMM/dd/yyyy", "MMMMM/dd/yy", "dd MMMMM yyyy", "dd/MM/yy", "dd/MM/yyyy", "yyyy/MM/dd", "yyyy-MM-dd", "yyyy-dd-MM", "MM-dd-yyyy", "MM-dd-yy" }; /** * Encapsulates constants relevant for build results and makes them localizable. */ public enum ResultState { OK( ContinuumProjectState.OK, "projectBuilds.report.resultOk" ), FAILED( ContinuumProjectState.FAILED, "projectBuilds.report.resultFailed" ), ERROR( ContinuumProjectState.ERROR, "projectBuilds.report.resultError" ), BUILDING( ContinuumProjectState.BUILDING, "projectBuilds.report.resultBuilding" ), CANCELLED( ContinuumProjectState.CANCELLED, "projectBuilds.report.resultCanceled" ); private static final Map<Integer, ResultState> dataMap; static { dataMap = new HashMap<Integer, ResultState>(); for ( ResultState val : ResultState.values() ) { dataMap.put( val.dataId, val ); } } private int dataId; private String textKey; ResultState( int dataId, String textKey ) { this.dataId = dataId; this.textKey = textKey; } public int getDataId() { return dataId; } public String getTextKey() { return textKey; } public static ResultState fromId( int state ) { return dataMap.get( state ); } public static boolean knownState( int state ) { return dataMap.containsKey( state ); } } private int buildStatus; private String triggeredBy = ""; private String startDate = ""; private String endDate = ""; private int projectGroupId; private int rowCount = 25; private int page = 1; private int pageTotal; private Map<Integer, String> buildStatuses; private Map<Integer, String> groupSelections; private Map<String, Integer> permittedGroupMap; private List<BuildResult> filteredResults; private HttpServletResponse rawResponse; public void setServletResponse( HttpServletResponse response ) { this.rawResponse = response; } protected boolean isAuthorized( String projectGroupName ) { try { checkViewProjectGroupAuthorization( projectGroupName ); return true; } catch ( AuthorizationRequiredException authzE ) { return false; } } public void prepare() throws Exception { super.prepare(); Collection<ProjectGroup> permittedGroups = getAuthorizedGroups(); groupSelections = createGroupSelections( permittedGroups ); permittedGroupMap = createPermittedGroupMap( permittedGroups ); buildStatuses = createStatusSelections(); } protected Map<String, Integer> createPermittedGroupMap( Collection<ProjectGroup> allowedGroups ) { Map<String, Integer> result = new HashMap<String, Integer>(); for ( ProjectGroup group : allowedGroups ) { result.put( group.getName(), group.getId() ); } return result; } protected Map<Integer, String> createGroupSelections( Collection<ProjectGroup> permittedGroups ) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); result.put( 0, "ALL" ); for ( ProjectGroup group : permittedGroups ) { result.put( group.getId(), group.getName() ); } return result; } protected Map<Integer, String> createStatusSelections() { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); result.put( 0, "ALL" ); for ( ResultState state : ResultState.values() ) { result.put( state.getDataId(), getText( state.getTextKey() ) ); } return result; } protected Collection<ProjectGroup> getAuthorizedGroups() { Collection<ProjectGroup> permitted = new ArrayList<ProjectGroup>(); List<ProjectGroup> groups = getContinuum().getAllProjectGroups(); if ( groups != null ) { for ( ProjectGroup group : groups ) { String groupName = group.getName(); if ( isAuthorized( groupName ) ) { permitted.add( group ); } } } return permitted; } public String init() { try { checkViewReportsAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } if ( permittedGroupMap.isEmpty() ) { addActionError( getText( "projectBuilds.report.noGroupsAuthorized" ) ); return REQUIRES_AUTHORIZATION; } // action class was called from the Menu; do not generate report first return SUCCESS; } public String execute() { try { checkViewReportsAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } if ( permittedGroupMap.isEmpty() ) { addActionError( getText( "projectBuilds.report.noGroupsAuthorized" ) ); return REQUIRES_AUTHORIZATION; } Date fromDate; Date toDate; try { fromDate = getStartDateInDateFormat(); toDate = getEndDateInDateFormat(); } catch ( ParseException e ) { addActionError( getText( "projectBuilds.report.badDates", new String[] { e.getMessage() } ) ); return INPUT; } if ( fromDate != null && toDate != null && fromDate.after( toDate ) ) { addFieldError( "startDate", getText( "projectBuilds.report.endBeforeStartDate" ) ); return INPUT; } // Limit query to scan only what the user is permitted to see Collection<Integer> groupIds = new HashSet<Integer>(); if ( projectGroupId > 0 ) { groupIds.add( projectGroupId ); } else { groupIds.addAll( permittedGroupMap.values() ); } filteredResults = getContinuum().getBuildResultsInRange( groupIds, fromDate, toDate, buildStatus, triggeredBy, 0, MAX_BROWSE_SIZE ); int resultSize = filteredResults.size(); if ( filteredResults.size() == MAX_BROWSE_SIZE ) { addActionMessage( getText( "projectBuilds.report.limitedResults" ) ); } pageTotal = resultSize / rowCount + ( resultSize % rowCount == 0 ? 0 : 1 ); if ( resultSize > 0 && ( page < 1 || page > pageTotal ) ) { addActionError( getText( "projectBuilds.report.invalidPage" ) ); return INPUT; } int pageStart = rowCount * ( page - 1 ), pageEnd = rowCount * page; // Restrict results to just the page we will show filteredResults = filteredResults.subList( pageStart, pageEnd > resultSize ? resultSize : pageEnd ); return SUCCESS; } /* * Export Builds Report to .csv */ public String downloadBuildsReport() { try { checkViewReportsAuthorization(); } catch ( AuthorizationRequiredException authzE ) { addActionError( authzE.getMessage() ); return REQUIRES_AUTHORIZATION; } if ( permittedGroupMap.isEmpty() ) { addActionError( getText( "projectBuilds.report.noGroupsAuthorized" ) ); return REQUIRES_AUTHORIZATION; } Date fromDate; Date toDate; try { fromDate = getStartDateInDateFormat(); toDate = getEndDateInDateFormat(); } catch ( ParseException e ) { addActionError( getText( "projectBuilds.report.badDates", new String[] { e.getMessage() } ) ); return INPUT; } if ( fromDate != null && toDate != null && fromDate.after( toDate ) ) { addFieldError( "startDate", getText( "projectBuilds.report.endBeforeStartDate" ) ); return INPUT; } try { // HTTP headers so the browser treats the file nicely for the user rawResponse.setContentType( "text/csv" ); rawResponse.addHeader( "Content-disposition", "attachment;filename=continuum_project_builds_report.csv" ); Writer output = rawResponse.getWriter(); DateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ); // Now, stream the file to the browser in pieces try { // Write the CSV file header output.append( "Group,Project,ID,Build#,Started,Duration,Triggered By,Status\n" ); // Limit query to scan only what the user is permitted to see Collection<Integer> groupIds = new HashSet<Integer>(); if ( projectGroupId > 0 ) { groupIds.add( projectGroupId ); } else { groupIds.addAll( permittedGroupMap.values() ); } // Build the output file by walking through the results in batches int offset = 0, exported = 0; List<BuildResult> results; export: do { results = getContinuum().getBuildResultsInRange( groupIds, fromDate, toDate, buildStatus, triggeredBy, offset, EXPORT_BATCH_SIZE ); // Ensure we advance through results offset += EXPORT_BATCH_SIZE; // Convert each build result to a line in the CSV file for ( BuildResult result : results ) { Project project = result.getProject(); ProjectGroup projectGroup = project.getProjectGroup(); int resultState = result.getState(); String stateName = ResultState.knownState( resultState ) ? getText( ResultState.fromId( resultState ).getTextKey() ) : getText( "projectBuilds.report.resultUnknown" ); String buildTime = dateTimeFormat.format( new Date( result.getStartTime() ) ); long buildDuration = ( result.getEndTime() - result.getStartTime() ) / 1000; String formattedLine = String.format( "%s,%s,%s,%s,%s,%s,%s,%s\n", projectGroup.getName(), project.getName(), result.getId(), result.getBuildNumber(), buildTime, buildDuration, result.getUsername(), stateName ); output.append( formattedLine ); exported += 1; if ( exported >= MAX_EXPORT_SIZE ) { log.warn( "build report export hit limit of {} records", MAX_EXPORT_SIZE ); break export; } } } while ( results.size() == EXPORT_BATCH_SIZE ); } finally { output.flush(); } } catch ( IOException e ) { addActionError( getText( "projectBuilds.report.exportIOError", new String[] { e.getMessage() } ) ); return INPUT; } return null; } private Date getStartDateInDateFormat() throws ParseException { Date date = null; if ( !StringUtils.isEmpty( startDate ) ) { date = DateUtils.parseDate( startDate, datePatterns ); } return date; } private Date getEndDateInDateFormat() throws ParseException { Date date = null; if ( !StringUtils.isEmpty( endDate ) ) { date = DateUtils.parseDate( endDate, datePatterns ); } return date; } public int getBuildStatus() { return this.buildStatus; } public void setBuildStatus( int buildStatus ) { this.buildStatus = buildStatus; } public int getProjectGroupId() { return this.projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getTriggeredBy() { return this.triggeredBy; } public void setTriggeredBy( String triggeredBy ) { this.triggeredBy = triggeredBy; } public String getStartDate() { return this.startDate; } public void setStartDate( String startDate ) { this.startDate = startDate; } public String getEndDate() { return this.endDate; } public void setEndDate( String endDate ) { this.endDate = endDate; } public int getRowCount() { return rowCount; } public Map<Integer, String> getBuildStatuses() { return buildStatuses; } public int getPage() { return page; } public void setPage( int page ) { this.page = page; } public int getPageTotal() { return pageTotal; } public List<BuildResult> getFilteredResults() { return filteredResults; } public Map<Integer, String> getProjectGroups() { return groupSelections; } }
5,568
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/DistributedReleasesAction.java
package org.apache.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.model.DistributedReleaseSummary; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Component( role = com.opensymphony.xwork2.Action.class, hint = "distributedRelease", instantiationStrategy = "per-lookup" ) public class DistributedReleasesAction extends ContinuumActionSupport implements SecureAction { private List<DistributedReleaseSummary> releasesSummary; public String list() throws Exception { DistributedReleaseManager releaseManager = getContinuum().getDistributedReleaseManager(); List<Map<String, Object>> releases = releaseManager.getAllReleasesInProgress(); releasesSummary = new ArrayList<DistributedReleaseSummary>(); for ( Map<String, Object> release : releases ) { DistributedReleaseSummary summary = new DistributedReleaseSummary(); summary.setReleaseId( DistributedReleaseUtil.getReleaseId( release ) ); summary.setReleaseGoal( DistributedReleaseUtil.getReleaseGoal( release ) ); summary.setBuildAgentUrl( DistributedReleaseUtil.getBuildAgentUrl( release ) ); summary.setProjectId( DistributedReleaseUtil.getProjectId( release ) ); releasesSummary.add( summary ); } return SUCCESS; } public List<DistributedReleaseSummary> getReleasesSummary() { return releasesSummary; } public void setReleasesSummary( List<DistributedReleaseSummary> releasesSummary ) { this.releasesSummary = releasesSummary; } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_VIEW_RELEASE, Resource.GLOBAL ); return bundle; } }
5,569
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/ScmResultAction.java
package org.apache.continuum.web.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.util.StateGenerator; import org.apache.struts2.ServletActionContext; import org.codehaus.plexus.component.annotations.Component; /** * @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "scmResult", instantiationStrategy = "per-lookup" ) public class ScmResultAction extends ContinuumActionSupport { private int projectGroupId; private int projectScmRootId; private String projectGroupName; private String state; private ProjectScmRoot projectScmRoot; public String execute() throws Exception { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } projectScmRoot = getContinuum().getProjectScmRoot( projectScmRootId ); state = StateGenerator.generate( projectScmRoot.getState(), ServletActionContext.getRequest().getContextPath() ); return SUCCESS; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getProjectScmRootId() { return projectScmRootId; } public void setProjectScmRootId( int projectScmRootId ) { this.projectScmRootId = projectScmRootId; } public ProjectScmRoot getProjectScmRoot() { return projectScmRoot; } public void setProjectScmRoot( ProjectScmRoot projectScmRoot ) { this.projectScmRoot = projectScmRoot; } public String getProjectGroupName() throws ContinuumException { projectGroupName = getContinuum().getProjectGroup( getProjectGroupId() ).getName(); return projectGroupName; } public void setProjectGroupName( String projectGroupName ) { this.projectGroupName = projectGroupName; } public String getState() { return state; } public void setState( String state ) { this.state = state; } }
5,570
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/admin/LocalRepositoryAction.java
package org.apache.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.ContinuumPurgeManager; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.continuum.repository.RepositoryService; import org.apache.continuum.taskqueue.manager.TaskQueueManager; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Maria Catherine Tan * @since 25 jul 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "localRepository", instantiationStrategy = "per-lookup" ) public class LocalRepositoryAction extends ContinuumConfirmAction implements Preparable, SecureAction { private static final String LAYOUT_DEFAULT = "default"; private static final String LAYOUT_LEGACY = "legacy"; private boolean confirmed; private boolean defaultRepo; private LocalRepository repository; private List<LocalRepository> repositories; private List<ProjectGroup> groups; private List<String> layouts; private Map<String, Boolean> defaultPurgeMap; @Requirement private RepositoryService repositoryService; @Requirement private PurgeConfigurationService purgeConfigService; public void prepare() throws Exception { super.prepare(); layouts = new ArrayList<String>(); layouts.add( LAYOUT_DEFAULT ); layouts.add( LAYOUT_LEGACY ); } public String input() throws Exception { defaultRepo = false; if ( repository != null && repository.getId() > 0 ) { repository = repositoryService.getLocalRepository( repository.getId() ); if ( repository.getName().equals( "DEFAULT" ) ) { defaultRepo = true; } } return INPUT; } public String list() throws Exception { repositories = repositoryService.getAllLocalRepositories(); defaultPurgeMap = new HashMap<String, Boolean>(); for ( LocalRepository repo : repositories ) { // get default purge config of repository RepositoryPurgeConfiguration purgeConfig = purgeConfigService.getDefaultPurgeConfigurationForRepository( repo.getId() ); if ( purgeConfig == null ) { defaultPurgeMap.put( repo.getName(), Boolean.FALSE ); } else { defaultPurgeMap.put( repo.getName(), Boolean.TRUE ); } } return SUCCESS; } public String save() throws Exception { List<LocalRepository> allRepositories = repositoryService.getAllLocalRepositories(); for ( LocalRepository repo : allRepositories ) { if ( repository.getId() != repo.getId() ) { if ( repository.getName().trim().equals( repo.getName() ) ) { addActionError( getText( "repository.error.name.unique" ) ); } if ( repository.getLocation().trim().equals( repo.getLocation() ) ) { addActionError( getText( "repository.error.location.unique" ) ); } } } if ( repository.getName().trim().equals( "" ) ) { addActionError( getText( "repository.error.name.cannot.be.spaces" ) ); } if ( repository.getLocation().trim().equals( "" ) ) { addActionError( getText( "repository.error.location.cannot.be.spaces" ) ); } if ( hasActionErrors() ) { return INPUT; } // trim repository name and location before saving repository.setName( repository.getName().trim() ); repository.setLocation( repository.getLocation().trim() ); if ( repository.getId() == 0 ) { repository = repositoryService.addLocalRepository( repository ); createDefaultPurgeConfiguration(); } else { // check if repository is in use TaskQueueManager taskQueueManager = getContinuum().getTaskQueueManager(); if ( taskQueueManager.isRepositoryInUse( repository.getId() ) ) { addActionError( getText( "repository.error.save.in.use" ) ); return ERROR; } LocalRepository retrievedRepo = repositoryService.getLocalRepository( repository.getId() ); retrievedRepo.setName( repository.getName() ); retrievedRepo.setLocation( repository.getLocation() ); retrievedRepo.setLayout( repository.getLayout() ); repositoryService.updateLocalRepository( retrievedRepo ); } return SUCCESS; } public String remove() throws Exception { TaskQueueManager taskQueueManager = getContinuum().getTaskQueueManager(); repository = repositoryService.getLocalRepository( repository.getId() ); if ( taskQueueManager.isRepositoryInUse( repository.getId() ) ) { addActionError( getText( "repository.error.remove.in.use", "Unable to remove local repository because it is in use" ) ); return ERROR; } if ( repository.getName().equals( "DEFAULT" ) ) { addActionError( getText( "repository.error.remove.default", "Unable to remove default local repository" ) ); return ERROR; } if ( !confirmed ) { return CONFIRM; } repositoryService.removeLocalRepository( repository.getId() ); addActionMessage( getText( "repository.remove.success" ) ); return SUCCESS; } public String doPurge() throws Exception { ContinuumPurgeManager purgeManager = getContinuum().getPurgeManager(); TaskQueueManager taskQueueManager = getContinuum().getTaskQueueManager(); // check if repository is in use if ( taskQueueManager.isRepositoryInUse( repository.getId() ) ) { addActionError( getText( "repository.error.purge.in.use", "Unable to purge repository because it is in use" ) ); return ERROR; } // get default purge configuration for repository RepositoryPurgeConfiguration purgeConfig = purgeConfigService.getDefaultPurgeConfigurationForRepository( repository.getId() ); if ( purgeConfig != null ) { purgeManager.purgeRepository( purgeConfig ); AuditLog event = new AuditLog( "Repository id=" + repository.getId(), AuditLogConstants.PURGE_LOCAL_REPOSITORY ); event.setCategory( AuditLogConstants.LOCAL_REPOSITORY ); event.setCurrentUser( getPrincipal() ); event.log(); addActionMessage( getText( "repository.purge.success" ) ); return SUCCESS; } addActionError( getText( "repository.error.not.found", new String[] { Integer.toString( repository.getId() ) } ) ); return ERROR; } public LocalRepository getRepository() { return this.repository; } public void setRepository( LocalRepository repository ) { this.repository = repository; } public List<LocalRepository> getRepositories() { return this.repositories; } public void setRepositories( List<LocalRepository> repositories ) { this.repositories = repositories; } public List<ProjectGroup> getGroups() { return this.groups; } public void setGroups( List<ProjectGroup> groups ) { this.groups = groups; } public boolean isConfirmed() { return this.confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public boolean isDefaultRepo() { return this.defaultRepo; } public void setDefaultRepo( boolean defaultRepo ) { this.defaultRepo = defaultRepo; } public List<String> getLayouts() { return this.layouts; } public Map<String, Boolean> getDefaultPurgeMap() { return this.defaultPurgeMap; } public void setDefaultPurgeMap( Map<String, Boolean> defaultPurgeMap ) { this.defaultPurgeMap = defaultPurgeMap; } private void createDefaultPurgeConfiguration() throws Exception { RepositoryPurgeConfiguration repoPurge = new RepositoryPurgeConfiguration(); repoPurge.setRepository( repository ); repoPurge.setDefaultPurge( true ); purgeConfigService.addRepositoryPurgeConfiguration( repoPurge ); } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_REPOSITORIES, Resource.GLOBAL ); return bundle; } }
5,571
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/admin/PurgeConfigurationAction.java
package org.apache.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.commons.lang.StringEscapeUtils; import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.ContinuumPurgeManager; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.continuum.repository.RepositoryService; import org.apache.continuum.taskqueue.manager.TaskQueueManager; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Maria Catherine Tan * @since 25 jul 07 */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "purgeConfiguration", instantiationStrategy = "per-lookup" ) public class PurgeConfigurationAction extends ContinuumConfirmAction implements Preparable, SecureAction { private static final String PURGE_TYPE_REPOSITORY = "repository"; private static final String PURGE_TYPE_DIRECTORY = "directory"; private static final String PURGE_DIRECTORY_RELEASES = "releases"; private static final String PURGE_DIRECTORY_BUILDOUTPUT = "buildOutput"; private static final int DEFAULT_RETENTION_COUNT = 2; private static final int DEFAULT_DAYS_OLDER = 100; private String purgeType; private String directoryType; private String description; private boolean deleteAll; private boolean deleteReleasedSnapshots; private boolean enabled; private boolean confirmed; private boolean defaultPurgeConfiguration; private int retentionCount; private int daysOlder; private int repositoryId; private int scheduleId; private int purgeConfigId; private AbstractPurgeConfiguration purgeConfig; private Map<Integer, String> repositories; private Map<Integer, String> schedules; private List<RepositoryPurgeConfiguration> repoPurgeConfigs; private List<DirectoryPurgeConfiguration> dirPurgeConfigs; private List<String> directoryTypes; @Requirement private PurgeConfigurationService purgeConfigService; @Requirement private RepositoryService repositoryService; @Override public void prepare() throws Exception { super.prepare(); // build schedules if ( schedules == null ) { schedules = new HashMap<Integer, String>(); Collection<Schedule> allSchedules = getContinuum().getSchedules(); for ( Schedule schedule : allSchedules ) { schedules.put( schedule.getId(), schedule.getName() ); } } // build repositories if ( repositories == null ) { repositories = new HashMap<Integer, String>(); List<LocalRepository> allRepositories = repositoryService.getAllLocalRepositories(); for ( LocalRepository repository : allRepositories ) { repositories.put( repository.getId(), repository.getName() ); } } directoryTypes = new ArrayList<String>(); directoryTypes.add( PURGE_DIRECTORY_RELEASES ); directoryTypes.add( PURGE_DIRECTORY_BUILDOUTPUT ); } @Override public String input() throws Exception { if ( purgeConfigId != 0 ) { purgeConfig = purgeConfigService.getPurgeConfiguration( purgeConfigId ); if ( purgeConfig instanceof RepositoryPurgeConfiguration ) { RepositoryPurgeConfiguration repoPurge = (RepositoryPurgeConfiguration) purgeConfig; this.purgeType = PURGE_TYPE_REPOSITORY; this.daysOlder = repoPurge.getDaysOlder(); this.retentionCount = repoPurge.getRetentionCount(); this.deleteAll = repoPurge.isDeleteAll(); this.deleteReleasedSnapshots = repoPurge.isDeleteReleasedSnapshots(); this.enabled = repoPurge.isEnabled(); this.defaultPurgeConfiguration = repoPurge.isDefaultPurge(); this.description = repoPurge.getDescription(); if ( repoPurge.getRepository() != null ) { this.repositoryId = repoPurge.getRepository().getId(); } if ( repoPurge.getSchedule() != null ) { this.scheduleId = repoPurge.getSchedule().getId(); } } else if ( purgeConfig instanceof DirectoryPurgeConfiguration ) { DirectoryPurgeConfiguration dirPurge = (DirectoryPurgeConfiguration) purgeConfig; this.purgeType = PURGE_TYPE_DIRECTORY; this.daysOlder = dirPurge.getDaysOlder(); this.retentionCount = dirPurge.getRetentionCount(); this.directoryType = dirPurge.getDirectoryType(); this.deleteAll = dirPurge.isDeleteAll(); this.enabled = dirPurge.isEnabled(); this.defaultPurgeConfiguration = dirPurge.isDefaultPurge(); this.description = dirPurge.getDescription(); if ( dirPurge.getSchedule() != null ) { this.scheduleId = dirPurge.getSchedule().getId(); } } } else { this.retentionCount = DEFAULT_RETENTION_COUNT; this.daysOlder = DEFAULT_DAYS_OLDER; } return INPUT; } public String list() throws Exception { repoPurgeConfigs = purgeConfigService.getAllRepositoryPurgeConfigurations(); dirPurgeConfigs = purgeConfigService.getAllDirectoryPurgeConfigurations(); return SUCCESS; } public String save() throws Exception { if ( purgeConfigId == 0 ) { if ( purgeType.equals( PURGE_TYPE_REPOSITORY ) ) { purgeConfig = new RepositoryPurgeConfiguration(); } else { purgeConfig = new DirectoryPurgeConfiguration(); } purgeConfig = setupPurgeConfiguration( purgeConfig ); purgeConfig = purgeConfigService.addPurgeConfiguration( purgeConfig ); } else { purgeConfig = purgeConfigService.getPurgeConfiguration( purgeConfigId ); purgeConfig = setupPurgeConfiguration( purgeConfig ); purgeConfigService.updatePurgeConfiguration( purgeConfig ); } if ( purgeConfig.isDefaultPurge() ) { updateDefaultPurgeConfiguration(); } if ( purgeConfig.isEnabled() && purgeConfig.getSchedule() != null ) { getContinuum().activePurgeSchedule( purgeConfig.getSchedule() ); } return SUCCESS; } public String remove() throws Exception { if ( !confirmed ) { return CONFIRM; } purgeConfigService.removePurgeConfiguration( purgeConfigId ); addActionMessage( getText( "purgeConfig.removeSuccess" ) ); return SUCCESS; } public String purge() throws Exception { ContinuumPurgeManager purgeManager = getContinuum().getPurgeManager(); TaskQueueManager taskQueueManager = getContinuum().getTaskQueueManager(); if ( purgeConfigId > 0 ) { purgeConfig = purgeConfigService.getPurgeConfiguration( purgeConfigId ); AuditLog event; if ( purgeConfig instanceof RepositoryPurgeConfiguration ) { RepositoryPurgeConfiguration repoPurge = (RepositoryPurgeConfiguration) purgeConfig; // check if repository is in use if ( taskQueueManager.isRepositoryInUse( repoPurge.getRepository().getId() ) ) { addActionError( getText( "repository.error.purge.in.use" ) ); return ERROR; } purgeManager.purgeRepository( repoPurge ); event = new AuditLog( repoPurge.getRepository().getName(), AuditLogConstants.PURGE_LOCAL_REPOSITORY ); event.setCategory( AuditLogConstants.LOCAL_REPOSITORY ); } else if ( purgeConfig instanceof DirectoryPurgeConfiguration ) { DirectoryPurgeConfiguration dirPurge = (DirectoryPurgeConfiguration) purgeConfig; purgeManager.purgeDirectory( dirPurge ); if ( dirPurge.getDirectoryType().equals( PURGE_DIRECTORY_RELEASES ) ) { event = new AuditLog( dirPurge.getLocation(), AuditLogConstants.PURGE_DIRECTORY_RELEASES ); } else { event = new AuditLog( dirPurge.getLocation(), AuditLogConstants.PURGE_DIRECTORY_BUILDOUTPUT ); } event.setCategory( AuditLogConstants.DIRECTORY ); } else { addActionError( getText( "purgeConfig.unknownType" ) ); return ERROR; } addActionMessage( getText( "purgeConfig.purgeSuccess" ) ); event.setCurrentUser( getPrincipal() ); event.log(); } return SUCCESS; } public String getPurgeType() { return this.purgeType; } public void setPurgeType( String purgeType ) { this.purgeType = purgeType; } public String getDirectoryType() { return this.directoryType; } public void setDirectoryType( String directoryType ) { this.directoryType = directoryType; } public String getDescription() { return this.description; } public void setDescription( String description ) { this.description = description; } public boolean isDeleteAll() { return this.deleteAll; } public void setDeleteAll( boolean deleteAll ) { this.deleteAll = deleteAll; } public boolean isDeleteReleasedSnapshots() { return this.deleteReleasedSnapshots; } public void setDeleteReleasedSnapshots( boolean deleteReleasedSnapshots ) { this.deleteReleasedSnapshots = deleteReleasedSnapshots; } public boolean isEnabled() { return this.enabled; } public void setEnabled( boolean enabled ) { this.enabled = enabled; } @Override public boolean isConfirmed() { return this.confirmed; } @Override public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public boolean isDefaultPurgeConfiguration() { return this.defaultPurgeConfiguration; } public void setDefaultPurgeConfiguration( boolean defaultPurgeConfiguration ) { this.defaultPurgeConfiguration = defaultPurgeConfiguration; } public int getRetentionCount() { return this.retentionCount; } public void setRetentionCount( int retentionCount ) { this.retentionCount = retentionCount; } public int getDaysOlder() { return this.daysOlder; } public void setDaysOlder( int daysOlder ) { this.daysOlder = daysOlder; } public int getRepositoryId() { return this.repositoryId; } public void setRepositoryId( int repositoryId ) { this.repositoryId = repositoryId; } public int getScheduleId() { return this.scheduleId; } public void setScheduleId( int scheduleId ) { this.scheduleId = scheduleId; } public int getPurgeConfigId() { return purgeConfigId; } public void setPurgeConfigId( int purgeConfigId ) { this.purgeConfigId = purgeConfigId; } public AbstractPurgeConfiguration getPurgeConfig() { return this.purgeConfig; } public void setPurgeConfig( AbstractPurgeConfiguration purgeConfig ) { this.purgeConfig = purgeConfig; } public Map<Integer, String> getRepositories() { return this.repositories; } public void setRepositories( Map<Integer, String> repositories ) { this.repositories = repositories; } public Map<Integer, String> getSchedules() { return this.schedules; } public void setSchedules( Map<Integer, String> schedules ) { this.schedules = schedules; } public List<RepositoryPurgeConfiguration> getRepoPurgeConfigs() { return this.repoPurgeConfigs; } public void setRepoPurgeConfigs( List<RepositoryPurgeConfiguration> repoPurgeConfigs ) { this.repoPurgeConfigs = repoPurgeConfigs; } public List<DirectoryPurgeConfiguration> getDirPurgeConfigs() { return this.dirPurgeConfigs; } public void setDirPurgeConfigs( List<DirectoryPurgeConfiguration> dirPurgeConfigs ) { this.dirPurgeConfigs = dirPurgeConfigs; } public List<String> getDirectoryTypes() { return this.directoryTypes; } public void setDirectoryTypes( List<String> directoryTypes ) { this.directoryTypes = directoryTypes; } private AbstractPurgeConfiguration setupPurgeConfiguration( AbstractPurgeConfiguration purgeConfiguration ) throws Exception { if ( purgeConfiguration instanceof RepositoryPurgeConfiguration ) { return buildRepoPurgeConfiguration(); } else { return buildDirPurgeConfiguration(); } } private RepositoryPurgeConfiguration buildRepoPurgeConfiguration() throws Exception { RepositoryPurgeConfiguration repoPurge = (RepositoryPurgeConfiguration) purgeConfig; repoPurge.setDeleteAll( this.deleteAll ); repoPurge.setDeleteReleasedSnapshots( this.deleteReleasedSnapshots ); repoPurge.setDaysOlder( this.daysOlder ); repoPurge.setRetentionCount( this.retentionCount ); repoPurge.setEnabled( this.enabled ); repoPurge.setDefaultPurge( this.defaultPurgeConfiguration ); // escape xml to prevent xss attacks repoPurge.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( this.description ) ) ); repoPurge.setDefaultPurge( this.defaultPurgeConfiguration ); if ( repositoryId != 0 ) { LocalRepository repository = repositoryService.getLocalRepository( repositoryId ); repoPurge.setRepository( repository ); } if ( scheduleId > 0 ) { Schedule schedule = getContinuum().getSchedule( scheduleId ); repoPurge.setSchedule( schedule ); } return repoPurge; } private DirectoryPurgeConfiguration buildDirPurgeConfiguration() throws Exception { DirectoryPurgeConfiguration dirPurge = (DirectoryPurgeConfiguration) purgeConfig; dirPurge.setDeleteAll( this.deleteAll ); dirPurge.setEnabled( this.enabled ); dirPurge.setDaysOlder( this.daysOlder ); dirPurge.setRetentionCount( this.retentionCount ); // escape xml to prevent xss attacks dirPurge.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( this.description ) ) ); dirPurge.setDirectoryType( this.directoryType ); dirPurge.setDefaultPurge( this.defaultPurgeConfiguration ); if ( scheduleId > 0 ) { Schedule schedule = getContinuum().getSchedule( scheduleId ); dirPurge.setSchedule( schedule ); } ConfigurationService configService = getContinuum().getConfiguration(); String path = null; if ( this.directoryType.equals( PURGE_DIRECTORY_RELEASES ) ) { path = configService.getWorkingDirectory().getAbsolutePath(); } else if ( this.directoryType.equals( PURGE_DIRECTORY_BUILDOUTPUT ) ) { path = configService.getBuildOutputDirectory().getAbsolutePath(); } dirPurge.setLocation( path ); return dirPurge; } private void updateDefaultPurgeConfiguration() throws Exception { if ( purgeConfig instanceof RepositoryPurgeConfiguration ) { RepositoryPurgeConfiguration repoPurge = purgeConfigService.getDefaultPurgeConfigurationForRepository( repositoryId ); if ( repoPurge != null && repoPurge.getId() != purgeConfig.getId() ) { repoPurge.setDefaultPurge( false ); purgeConfigService.updateRepositoryPurgeConfiguration( repoPurge ); } } else if ( purgeConfig instanceof DirectoryPurgeConfiguration ) { DirectoryPurgeConfiguration dirPurge = purgeConfigService.getDefaultPurgeConfigurationForDirectoryType( directoryType ); if ( dirPurge != null && dirPurge.getId() != purgeConfig.getId() ) { dirPurge.setDefaultPurge( false ); purgeConfigService.updateDirectoryPurgeConfiguration( dirPurge ); } } } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PURGING, Resource.GLOBAL ); return bundle; } }
5,572
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/admin/PurgeAction.java
package org.apache.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedRepositoryPurgeConfiguration; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @Component( role = com.opensymphony.xwork2.Action.class, hint = "purge", instantiationStrategy = "per-lookup" ) public class PurgeAction extends ContinuumConfirmAction implements Preparable, SecureAction { private static final String DISTRIBUTED_BUILD_SUCCESS = "distributed-build-success"; private Map<Integer, String> repositories; private Map<Integer, String> schedules; private List<RepositoryPurgeConfiguration> repoPurgeConfigs; private List<DirectoryPurgeConfiguration> dirPurgeConfigs; private List<DistributedDirectoryPurgeConfiguration> distributedDirPurgeConfigs; private List<DistributedRepositoryPurgeConfiguration> distributedRepoPurgeConfigs; private List<String> directoryTypes; @Requirement private PurgeConfigurationService purgeConfigService; @Override public void prepare() throws Exception { super.prepare(); schedules = new HashMap<Integer, String>(); Collection<Schedule> allSchedules = getContinuum().getSchedules(); for ( Schedule schedule : allSchedules ) { schedules.put( schedule.getId(), schedule.getName() ); } } public String display() throws Exception { if ( getContinuum().getConfiguration().isDistributedBuildEnabled() ) { distributedDirPurgeConfigs = purgeConfigService.getAllDistributedDirectoryPurgeConfigurations(); distributedRepoPurgeConfigs = purgeConfigService.getAllDistributedRepositoryPurgeConfigurations(); return DISTRIBUTED_BUILD_SUCCESS; } else { repoPurgeConfigs = purgeConfigService.getAllRepositoryPurgeConfigurations(); dirPurgeConfigs = purgeConfigService.getAllDirectoryPurgeConfigurations(); return SUCCESS; } } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PURGING, Resource.GLOBAL ); return bundle; } public Map<Integer, String> getRepositories() { return repositories; } public void setRepositories( Map<Integer, String> repositories ) { this.repositories = repositories; } public List<RepositoryPurgeConfiguration> getRepoPurgeConfigs() { return repoPurgeConfigs; } public void setRepoPurgeConfigs( List<RepositoryPurgeConfiguration> repoPurgeConfigs ) { this.repoPurgeConfigs = repoPurgeConfigs; } public List<DirectoryPurgeConfiguration> getDirPurgeConfigs() { return dirPurgeConfigs; } public void setDirPurgeConfigs( List<DirectoryPurgeConfiguration> dirPurgeConfigs ) { this.dirPurgeConfigs = dirPurgeConfigs; } public List<DistributedDirectoryPurgeConfiguration> getDistributedDirPurgeConfigs() { return distributedDirPurgeConfigs; } public void setDistributedDirPurgeConfigs( List<DistributedDirectoryPurgeConfiguration> distributedDirPurgeConfigs ) { this.distributedDirPurgeConfigs = distributedDirPurgeConfigs; } public List<DistributedRepositoryPurgeConfiguration> getDistributedRepoPurgeConfigs() { return distributedRepoPurgeConfigs; } public void setDistributedRepoPurgeConfigs( List<DistributedRepositoryPurgeConfiguration> distributedRepoPurgeConfigs ) { this.distributedRepoPurgeConfigs = distributedRepoPurgeConfigs; } public List<String> getDirectoryTypes() { return directoryTypes; } public void setDirectoryTypes( List<String> directoryTypes ) { this.directoryTypes = directoryTypes; } public PurgeConfigurationService getPurgeConfigService() { return purgeConfigService; } public void setPurgeConfigService( PurgeConfigurationService purgeConfigService ) { this.purgeConfigService = purgeConfigService; } }
5,573
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/admin/DistributedPurgeConfigurationAction.java
package org.apache.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.opensymphony.xwork2.Preparable; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedRepositoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.purge.ContinuumPurgeManager; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.continuum.repository.RepositoryService; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @Component( role = com.opensymphony.xwork2.Action.class, hint = "distributedPurgeConfiguration", instantiationStrategy = "per-lookup" ) public class DistributedPurgeConfigurationAction extends ContinuumConfirmAction implements Preparable, SecureAction { private static final Logger logger = LoggerFactory.getLogger( DistributedPurgeConfigurationAction.class ); private static final String PURGE_TYPE_DIRECTORY = "directory"; private static final String PURGE_TYPE_REPOSITORY = "repository"; private static final String PURGE_DIRECTORY_RELEASES = "releases"; private static final String PURGE_DIRECTORY_WORKING = "working"; private static final int DEFAULT_RETENTION_COUNT = 2; private static final int DEFAULT_DAYS_OLDER = 100; private String repositoryName; private String purgeType; private String directoryType; private String description; private boolean deleteAll; private boolean deleteReleasedSnapshots; private boolean enabled; private boolean confirmed; private boolean defaultPurgeConfiguration; private int retentionCount; private int daysOlder; private int scheduleId; private int purgeConfigId; private String buildAgentUrl; private AbstractPurgeConfiguration purgeConfig; private Map<Integer, String> schedules; private List<String> repositories; private List<String> directoryTypes; private List<String> buildAgentUrls; @Requirement private PurgeConfigurationService purgeConfigService; @Requirement private RepositoryService repositoryService; @Override public void prepare() throws Exception { super.prepare(); // build schedules if ( schedules == null ) { schedules = new HashMap<Integer, String>(); Collection<Schedule> allSchedules = getContinuum().getSchedules(); for ( Schedule schedule : allSchedules ) { schedules.put( schedule.getId(), schedule.getName() ); } } // build repositories if ( repositories == null ) { repositories = new ArrayList<String>(); List<LocalRepository> allRepositories = repositoryService.getAllLocalRepositories(); for ( LocalRepository repository : allRepositories ) { repositories.add( repository.getName() ); } } // build repositories if ( buildAgentUrls == null ) { List<BuildAgentConfiguration> buildAgents = getContinuum().getConfiguration().getBuildAgents(); buildAgentUrls = new ArrayList<String>( buildAgents.size() ); for ( BuildAgentConfiguration buildAgent : buildAgents ) { buildAgentUrls.add( buildAgent.getUrl() ); } Collections.sort( buildAgentUrls ); } directoryTypes = new ArrayList<String>(); directoryTypes.add( PURGE_DIRECTORY_RELEASES ); directoryTypes.add( PURGE_DIRECTORY_WORKING ); } @Override public String input() throws Exception { if ( purgeConfigId != 0 ) { // Shared configuration purgeConfig = purgeConfigService.getPurgeConfiguration( purgeConfigId ); this.daysOlder = purgeConfig.getDaysOlder(); this.retentionCount = purgeConfig.getRetentionCount(); this.deleteAll = purgeConfig.isDeleteAll(); this.enabled = purgeConfig.isEnabled(); this.defaultPurgeConfiguration = purgeConfig.isDefaultPurge(); this.description = purgeConfig.getDescription(); if ( purgeConfig.getSchedule() != null ) { this.scheduleId = purgeConfig.getSchedule().getId(); } if ( purgeConfig instanceof DistributedDirectoryPurgeConfiguration ) { // Custom dir configuration DistributedDirectoryPurgeConfiguration dirPurge = (DistributedDirectoryPurgeConfiguration) purgeConfig; this.purgeType = PURGE_TYPE_DIRECTORY; this.directoryType = dirPurge.getDirectoryType(); this.buildAgentUrl = dirPurge.getBuildAgentUrl(); } else if ( purgeConfig instanceof DistributedRepositoryPurgeConfiguration ) { // Custom repo configuration DistributedRepositoryPurgeConfiguration repoPurge = (DistributedRepositoryPurgeConfiguration) purgeConfig; this.purgeType = PURGE_TYPE_REPOSITORY; this.deleteReleasedSnapshots = repoPurge.isDeleteReleasedSnapshots(); this.buildAgentUrl = repoPurge.getBuildAgentUrl(); if ( !StringUtils.isEmpty( repoPurge.getRepositoryName() ) ) { this.repositoryName = repoPurge.getRepositoryName(); } } } else { this.retentionCount = DEFAULT_RETENTION_COUNT; this.daysOlder = DEFAULT_DAYS_OLDER; } return INPUT; } public String save() throws Exception { if ( purgeConfigId == 0 ) { if ( PURGE_TYPE_REPOSITORY.equals( purgeType ) ) { purgeConfig = new DistributedRepositoryPurgeConfiguration(); } else { purgeConfig = new DistributedDirectoryPurgeConfiguration(); } purgeConfig = setupPurgeConfiguration(); purgeConfig = purgeConfigService.addPurgeConfiguration( purgeConfig ); } else { purgeConfig = purgeConfigService.getPurgeConfiguration( purgeConfigId ); purgeConfig = setupPurgeConfiguration(); purgeConfigService.updatePurgeConfiguration( purgeConfig ); } /*if ( purgeConfig.isDefaultPurge() ) { updateDefaultPurgeConfiguration(); }*/ if ( purgeConfig.isEnabled() && purgeConfig.getSchedule() != null ) { getContinuum().activePurgeSchedule( purgeConfig.getSchedule() ); } return SUCCESS; } public String remove() throws Exception { if ( !confirmed ) { return CONFIRM; } purgeConfigService.removePurgeConfiguration( purgeConfigId ); addActionMessage( getText( "purgeConfig.removeSuccess" ) ); return SUCCESS; } public String purge() throws Exception { ContinuumPurgeManager purgeManager = getContinuum().getPurgeManager(); if ( purgeConfigId > 0 ) { purgeConfig = purgeConfigService.getPurgeConfiguration( purgeConfigId ); if ( purgeConfig instanceof DistributedDirectoryPurgeConfiguration ) { DistributedDirectoryPurgeConfiguration dirPurge = (DistributedDirectoryPurgeConfiguration) purgeConfig; purgeManager.purgeDistributedDirectory( dirPurge ); } else if ( purgeConfig instanceof DistributedRepositoryPurgeConfiguration ) { DistributedRepositoryPurgeConfiguration repoPurge = (DistributedRepositoryPurgeConfiguration) purgeConfig; purgeManager.purgeDistributedRepository( repoPurge ); } else { addActionError( getText( "purgeConfig.unknownType" ) ); return ERROR; } addActionMessage( getText( "purgeConfig.purgeSuccess" ) ); } return SUCCESS; } public String getPurgeType() { return this.purgeType; } public void setPurgeType( String purgeType ) { this.purgeType = purgeType; } public String getDirectoryType() { return this.directoryType; } public void setDirectoryType( String directoryType ) { this.directoryType = directoryType; } public String getDescription() { return this.description; } public void setDescription( String description ) { this.description = description; } public boolean isDeleteAll() { return this.deleteAll; } public void setDeleteAll( boolean deleteAll ) { this.deleteAll = deleteAll; } public boolean isDeleteReleasedSnapshots() { return this.deleteReleasedSnapshots; } public void setDeleteReleasedSnapshots( boolean deleteReleasedSnapshots ) { this.deleteReleasedSnapshots = deleteReleasedSnapshots; } public boolean isEnabled() { return this.enabled; } public void setEnabled( boolean enabled ) { this.enabled = enabled; } @Override public boolean isConfirmed() { return this.confirmed; } @Override public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public boolean isDefaultPurgeConfiguration() { return this.defaultPurgeConfiguration; } public void setDefaultPurgeConfiguration( boolean defaultPurgeConfiguration ) { this.defaultPurgeConfiguration = defaultPurgeConfiguration; } public int getRetentionCount() { return this.retentionCount; } public void setRetentionCount( int retentionCount ) { this.retentionCount = retentionCount; } public int getDaysOlder() { return this.daysOlder; } public void setDaysOlder( int daysOlder ) { this.daysOlder = daysOlder; } public int getScheduleId() { return this.scheduleId; } public void setScheduleId( int scheduleId ) { this.scheduleId = scheduleId; } public int getPurgeConfigId() { return purgeConfigId; } public void setPurgeConfigId( int purgeConfigId ) { this.purgeConfigId = purgeConfigId; } public AbstractPurgeConfiguration getPurgeConfig() { return this.purgeConfig; } public void setPurgeConfig( AbstractPurgeConfiguration purgeConfig ) { this.purgeConfig = purgeConfig; } public Map<Integer, String> getSchedules() { return this.schedules; } public void setSchedules( Map<Integer, String> schedules ) { this.schedules = schedules; } public List<String> getDirectoryTypes() { return this.directoryTypes; } public void setDirectoryTypes( List<String> directoryTypes ) { this.directoryTypes = directoryTypes; } public String getBuildAgentUrl() { return buildAgentUrl; } public void setBuildAgentUrl( String buildAgentUrl ) { this.buildAgentUrl = buildAgentUrl; } public List<String> getBuildAgentUrls() { return buildAgentUrls; } public void setBuildAgentUrls( List<String> buildAgentUrls ) { this.buildAgentUrls = buildAgentUrls; } private AbstractPurgeConfiguration setupPurgeConfiguration() throws Exception { purgeConfig.setDeleteAll( deleteAll ); purgeConfig.setEnabled( enabled ); purgeConfig.setDaysOlder( daysOlder ); purgeConfig.setRetentionCount( retentionCount ); purgeConfig.setDefaultPurge( defaultPurgeConfiguration ); // escape xml to prevent xss attacks purgeConfig.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( this.description ) ) ); if ( scheduleId > 0 ) { Schedule schedule = getContinuum().getSchedule( scheduleId ); purgeConfig.setSchedule( schedule ); } if ( purgeConfig instanceof DistributedDirectoryPurgeConfiguration ) { DistributedDirectoryPurgeConfiguration dirPurge = (DistributedDirectoryPurgeConfiguration) purgeConfig; dirPurge.setDirectoryType( directoryType ); dirPurge.setBuildAgentUrl( buildAgentUrl ); } else if ( purgeConfig instanceof DistributedRepositoryPurgeConfiguration ) { DistributedRepositoryPurgeConfiguration repoPurge = (DistributedRepositoryPurgeConfiguration) purgeConfig; repoPurge.setRepositoryName( repositoryName ); repoPurge.setDeleteReleasedSnapshots( deleteReleasedSnapshots ); repoPurge.setBuildAgentUrl( buildAgentUrl ); } return purgeConfig; } private void updateDefaultPurgeConfiguration() throws Exception { DirectoryPurgeConfiguration dirPurge = purgeConfigService.getDefaultPurgeConfigurationForDirectoryType( directoryType ); if ( dirPurge != null && dirPurge.getId() != purgeConfig.getId() ) { dirPurge.setDefaultPurge( false ); purgeConfigService.updateDirectoryPurgeConfiguration( dirPurge ); } } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PURGING, Resource.GLOBAL ); return bundle; } public List<String> getRepositories() { return this.repositories; } public void setRepositories( List<String> repositories ) { this.repositories = repositories; } public String getRepositoryName() { return repositoryName; } public void setRepositoryName( String repositoryName ) { this.repositoryName = repositoryName; } }
5,574
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/admin/BuildAgentAction.java
package org.apache.continuum.web.action.admin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringEscapeUtils; import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.web.util.AuditLog; import org.apache.continuum.web.util.AuditLogConstants; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.web.action.ContinuumConfirmAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.redback.rbac.Resource; import org.codehaus.plexus.util.StringUtils; import org.codehaus.redback.integration.interceptor.SecureAction; import org.codehaus.redback.integration.interceptor.SecureActionBundle; import org.codehaus.redback.integration.interceptor.SecureActionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Maria Catherine Tan */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "buildAgent", instantiationStrategy = "per-lookup" ) public class BuildAgentAction extends ContinuumConfirmAction implements SecureAction { private static final Logger logger = LoggerFactory.getLogger( BuildAgentAction.class ); private List<BuildAgentConfiguration> buildAgents; private BuildAgentConfiguration buildAgent; private BuildAgentGroupConfiguration buildAgentGroup; private List<BuildAgentGroupConfiguration> buildAgentGroups; private List<BuildAgentConfiguration> selectedbuildAgents; private List<String> selectedBuildAgentIds; private List<Installation> installations; private boolean confirmed; private String type; private String typeGroup; public void prepare() throws Exception { super.prepare(); this.setBuildAgents( getContinuum().getConfiguration().getBuildAgents() ); } public String input() throws Exception { if ( buildAgent != null && !StringUtils.isBlank( buildAgent.getUrl() ) ) { String escapedBuildAgentUrl = StringEscapeUtils.escapeXml( buildAgent.getUrl() ); buildAgent.setUrl( escapedBuildAgentUrl ); List<BuildAgentConfiguration> agents = getContinuum().getConfiguration().getBuildAgents(); for ( BuildAgentConfiguration agent : agents ) { if ( agent.getUrl().equals( escapedBuildAgentUrl ) ) { buildAgent = agent; type = "edit"; } } } else { type = "new"; buildAgent = new BuildAgentConfiguration(); buildAgent.setEnabled( true ); } return INPUT; } public String list() throws Exception { this.buildAgents = getContinuum().getConfiguration().getBuildAgents(); this.buildAgentGroups = getContinuum().getConfiguration().getBuildAgentGroups(); return SUCCESS; } public String view() throws Exception { ConfigurationService configuration = getContinuum().getConfiguration(); if ( buildAgent != null ) { for ( BuildAgentConfiguration agent : configuration.getBuildAgents() ) { if ( agent.getUrl().equals( buildAgent.getUrl() ) ) { buildAgent = agent; try { installations = getContinuum().getDistributedBuildManager().getAvailableInstallations( buildAgent.getUrl() ); } catch ( ContinuumException e ) { logger.error( "Unable to retrieve installations of build agent '" + agent.getUrl() + "'", e ); } break; } } } return SUCCESS; } public String save() throws Exception { boolean found = false; ConfigurationService configuration = getContinuum().getConfiguration(); // escape xml to prevent xss attacks buildAgent.setDescription( StringEscapeUtils.escapeXml( StringEscapeUtils.unescapeXml( buildAgent.getDescription() ) ) ); if ( configuration.getBuildAgents() != null ) { for ( BuildAgentConfiguration agent : configuration.getBuildAgents() ) { if ( agent.getUrl().equals( buildAgent.getUrl() ) ) { if ( type.equals( "new" ) ) { addActionError( getText( "buildAgent.error.duplicate" ) ); return INPUT; } else { agent.setDescription( buildAgent.getDescription() ); agent.setEnabled( buildAgent.isEnabled() ); configuration.updateBuildAgent( agent ); configuration.store(); } found = true; } } } // update first, so that we don't add or change it if it fails try { getContinuum().getDistributedBuildManager().update( buildAgent ); } catch ( ContinuumException e ) { addActionError( e.getMessage() ); return INPUT; } AuditLog event = new AuditLog( "Build Agent URL=" + buildAgent.getUrl(), AuditLogConstants.MODIFY_BUILD_AGENT ); event.setCategory( AuditLogConstants.BUILD_AGENT ); event.setCurrentUser( getPrincipal() ); if ( !found ) { configuration.addBuildAgent( buildAgent ); configuration.store(); event.setAction( AuditLogConstants.ADD_BUILD_AGENT ); } event.log(); return SUCCESS; } public String delete() throws Exception { buildAgent.setUrl( StringEscapeUtils.escapeXml( buildAgent.getUrl() ) ); if ( !confirmed ) { return CONFIRM; } if ( getContinuum().getDistributedBuildManager().isBuildAgentBusy( buildAgent.getUrl() ) ) { addActionError( getText( "buildAgent.error.delete.busy" ) ); return ERROR; } ConfigurationService configuration = getContinuum().getConfiguration(); if ( configuration.getBuildAgentGroups() != null ) { for ( BuildAgentGroupConfiguration buildAgentGroup : configuration.getBuildAgentGroups() ) { if ( configuration.containsBuildAgentUrl( buildAgent.getUrl(), buildAgentGroup ) ) { addActionError( getText( "buildAgent.error.remove.in.use" ) ); return ERROR; } } } if ( configuration.getBuildAgents() != null ) { for ( BuildAgentConfiguration agent : configuration.getBuildAgents() ) { if ( buildAgent.getUrl().equals( agent.getUrl() ) ) { getContinuum().getDistributedBuildManager().removeDistributedBuildQueueOfAgent( buildAgent.getUrl() ); configuration.removeBuildAgent( agent ); configuration.store(); AuditLog event = new AuditLog( "Build Agent URL=" + agent.getUrl(), AuditLogConstants.REMOVE_BUILD_AGENT ); event.setCategory( AuditLogConstants.BUILD_AGENT ); event.setCurrentUser( getPrincipal() ); event.log(); getContinuum().getDistributedBuildManager().reload(); return SUCCESS; } } } addActionError( getText( "buildAgent.error.notfound" ) ); return ERROR; } public String deleteGroup() throws Exception { buildAgentGroup.setName( StringEscapeUtils.escapeXml( buildAgentGroup.getName() ) ); if ( !confirmed ) { return CONFIRM; } List<Profile> profiles = getContinuum().getProfileService().getAllProfiles(); for ( Profile profile : profiles ) { if ( buildAgentGroup.getName().equals( profile.getBuildAgentGroup() ) ) { addActionError( getText( "buildAgentGroup.error.remove.in.use", new String[] { profile.getName() } ) ); return ERROR; } } ConfigurationService configuration = getContinuum().getConfiguration(); for ( BuildAgentGroupConfiguration group : configuration.getBuildAgentGroups() ) { if ( buildAgentGroup.getName().equals( group.getName() ) ) { configuration.removeBuildAgentGroup( group ); AuditLog event = new AuditLog( "Build Agent Group=" + group.getName(), AuditLogConstants.REMOVE_BUILD_AGENT_GROUP ); event.setCategory( AuditLogConstants.BUILD_AGENT ); event.setCurrentUser( getPrincipal() ); event.log(); return SUCCESS; } } addActionError( getText( "buildAgentGroup.error.doesnotexist" ) ); return ERROR; } public String saveGroup() throws Exception { boolean found = false; ConfigurationService configuration = getContinuum().getConfiguration(); selectedbuildAgents = getBuildAgentsFromSelectedBuildAgents(); if ( buildAgentGroup.getName() != null ) { if ( buildAgentGroup.getName().equals( "" ) ) { addActionError( getText( "buildAgentGroup.error.name.required" ) ); return INPUT; } else if ( buildAgentGroup.getName().trim().equals( "" ) ) { addActionError( getText( "buildAgentGroup.error.name.cannot.be.spaces" ) ); return INPUT; } } if ( configuration.getBuildAgentGroups() != null ) { for ( BuildAgentGroupConfiguration group : configuration.getBuildAgentGroups() ) { if ( buildAgentGroup.getName().equals( group.getName() ) ) { group.setName( buildAgentGroup.getName() ); configuration.updateBuildAgentGroup( group ); found = true; break; } } } AuditLog event = new AuditLog( "Build Agent Group=" + buildAgentGroup.getName(), AuditLogConstants.MODIFY_BUILD_AGENT_GROUP ); event.setCategory( AuditLogConstants.BUILD_AGENT ); event.setCurrentUser( getPrincipal() ); if ( !found ) { buildAgentGroup.setBuildAgents( selectedbuildAgents ); configuration.addBuildAgentGroup( buildAgentGroup ); event.setAction( AuditLogConstants.ADD_BUILD_AGENT_GROUP ); } else // found { if ( typeGroup.equals( "new" ) ) { addActionError( getText( "buildAgentGroup.error.duplicate" ) ); return INPUT; } else if ( typeGroup.equals( "edit" ) ) { buildAgentGroup.setBuildAgents( selectedbuildAgents ); configuration.updateBuildAgentGroup( buildAgentGroup ); } } getContinuum().getDistributedBuildManager().reload(); event.log(); return SUCCESS; } public String inputGroup() throws Exception { ConfigurationService configuration = getContinuum().getConfiguration(); if ( buildAgentGroup != null && !StringUtils.isBlank( buildAgentGroup.getName() ) ) { String escapedBuildAgentGroupName = StringEscapeUtils.escapeXml( buildAgentGroup.getName() ); buildAgentGroup.setName( escapedBuildAgentGroupName ); List<BuildAgentGroupConfiguration> agentGroups = configuration.getBuildAgentGroups(); for ( BuildAgentGroupConfiguration group : agentGroups ) { if ( group.getName().equals( escapedBuildAgentGroupName ) ) { buildAgentGroup = group; typeGroup = "edit"; this.buildAgentGroup = configuration.getBuildAgentGroup( escapedBuildAgentGroupName ); this.buildAgents = configuration.getBuildAgents(); this.selectedBuildAgentIds = new ArrayList<String>(); if ( this.buildAgentGroup.getBuildAgents() != null ) { for ( BuildAgentConfiguration buildAgentConfiguration : buildAgentGroup.getBuildAgents() ) { this.selectedBuildAgentIds.add( buildAgentConfiguration.getUrl() ); } } List<BuildAgentConfiguration> unusedBuildAgents = new ArrayList<BuildAgentConfiguration>(); for ( BuildAgentConfiguration agent : getBuildAgents() ) { if ( !this.selectedBuildAgentIds.contains( agent.getUrl() ) ) { unusedBuildAgents.add( agent ); } } this.setBuildAgents( unusedBuildAgents ); break; } } } else { buildAgentGroup = new BuildAgentGroupConfiguration(); typeGroup = "new"; } return INPUT; } public SecureActionBundle getSecureActionBundle() throws SecureActionException { SecureActionBundle bundle = new SecureActionBundle(); bundle.setRequiresAuthentication( true ); bundle.addRequiredAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_DISTRIBUTED_BUILDS, Resource.GLOBAL ); return bundle; } private List<BuildAgentConfiguration> getBuildAgentsFromSelectedBuildAgents() { if ( this.selectedBuildAgentIds == null ) { return Collections.EMPTY_LIST; } List<BuildAgentConfiguration> selectedbuildAgents = new ArrayList<BuildAgentConfiguration>(); for ( String ids : selectedBuildAgentIds ) { BuildAgentConfiguration buildAgent = getContinuum().getConfiguration().getBuildAgent( ids ); if ( buildAgent != null ) { selectedbuildAgents.add( buildAgent ); } } return selectedbuildAgents; } public List<BuildAgentConfiguration> getBuildAgents() { return buildAgents; } public void setBuildAgents( List<BuildAgentConfiguration> buildAgents ) { this.buildAgents = buildAgents; } public BuildAgentConfiguration getBuildAgent() { return buildAgent; } public void setBuildAgent( BuildAgentConfiguration buildAgent ) { this.buildAgent = buildAgent; } public List<Installation> getInstallations() { return installations; } public void setInstallations( List<Installation> installations ) { this.installations = installations; } public boolean isConfirmed() { return confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public String getType() { return type; } public void setType( String type ) { this.type = type; } public List<BuildAgentGroupConfiguration> getBuildAgentGroups() { return buildAgentGroups; } public void setBuildAgentGroups( List<BuildAgentGroupConfiguration> buildAgentGroups ) { this.buildAgentGroups = buildAgentGroups; } public BuildAgentGroupConfiguration getBuildAgentGroup() { return buildAgentGroup; } public void setBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) { this.buildAgentGroup = buildAgentGroup; } public String getTypeGroup() { return typeGroup; } public void setTypeGroup( String typeGroup ) { this.typeGroup = typeGroup; } public List<BuildAgentConfiguration> getSelectedbuildAgents() { return selectedbuildAgents; } public void setSelectedbuildAgents( List<BuildAgentConfiguration> selectedbuildAgents ) { this.selectedbuildAgents = selectedbuildAgents; } public List<String> getSelectedBuildAgentIds() { return selectedBuildAgentIds == null ? Collections.EMPTY_LIST : selectedBuildAgentIds; } public void setSelectedBuildAgentIds( List<String> selectedBuildAgentIds ) { this.selectedBuildAgentIds = selectedBuildAgentIds; } }
5,575
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/action/error/HttpError.java
package org.apache.continuum.web.action.error; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.web.action.ContinuumActionSupport; import org.codehaus.plexus.component.annotations.Component; /** * AboutAction: * * @author: Emmanuel Venisse <evenisse@apache.org> */ @Component( role = com.opensymphony.xwork2.Action.class, hint = "httpError", instantiationStrategy = "per-lookup" ) public class HttpError extends ContinuumActionSupport { private int errorCode; public String execute() throws Exception { return SUCCESS; } public int getErrorCode() { return errorCode; } public void setErrorCode( int errorCode ) { this.errorCode = errorCode; } }
5,576
0
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-webapp/src/main/java/org/apache/continuum/web/startup/ContinuumStartup.java
package org.apache.continuum.web.startup; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.maven.continuum.Continuum; import org.codehaus.plexus.spring.PlexusToSpringUtils; import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 15 mars 2008 */ public class ContinuumStartup implements ServletContextListener { private Logger log = LoggerFactory.getLogger( getClass() ); /** * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ public void contextDestroyed( ServletContextEvent sce ) { // nothing to do here } /** * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ public void contextInitialized( ServletContextEvent sce ) { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext( sce.getServletContext() ); // to simulate Plexus load on start with Spring Continuum continuum = (Continuum) wac.getBean( PlexusToSpringUtils.buildSpringId( Continuum.class ) ); BuildsManager buildsManager = (BuildsManager) wac.getBean( PlexusToSpringUtils.buildSpringId( BuildsManager.class, "parallel" ) ); TaskQueueExecutor prepareRelease = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "prepare-release" ) ); TaskQueueExecutor performRelease = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "perform-release" ) ); TaskQueueExecutor rollbackRelease = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "rollback-release" ) ); TaskQueueExecutor purge = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "purge" ) ); TaskQueueExecutor prepareBuildProject = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "prepare-build-project" ) ); DistributedBuildManager distributedBuildManager = (DistributedBuildManager) wac.getBean( PlexusToSpringUtils.buildSpringId( DistributedBuildManager.class ) ); } }
5,577
0
Create_ds/rack-servlet/core/src/test/java/com/squareup
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/SlowByteArrayInputStream.java
package com.squareup.rack; import java.io.ByteArrayInputStream; class SlowByteArrayInputStream extends ByteArrayInputStream { public SlowByteArrayInputStream(byte[] buf) { super(buf); } @Override public final int read(byte[] b, int off, int len) { if (pos >= count) { return -1; } if ((pos + len) > count) { len = (count - pos); } if (len <= 0) { return 0; } // Ensure we only read two bytes per read len = Math.min(len, 2); System.arraycopy(buf, pos, b, off, len); pos += len; return len; } }
5,578
0
Create_ds/rack-servlet/core/src/test/java/com/squareup
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/RackInputTest.java
package com.squareup.rack; import java.io.ByteArrayInputStream; import org.junit.Before; import org.junit.Test; import static java.util.Arrays.copyOfRange; import static org.fest.assertions.api.Assertions.assertThat; public class RackInputTest { public static final byte[] EMPTY_BYTES = "".getBytes(); public static final byte[] BYTES = "Hello,\nWorld!".getBytes(); private RackInput empty; private RackInput full; private RackInput fullSlow; @Before public void setUp() throws Exception { empty = rackInputFor(EMPTY_BYTES); full = rackInputFor(BYTES); fullSlow = slowRackInputFor(BYTES); } @Test public void getsAtEof() throws Exception { assertThat(empty.gets()).isNull(); } @Test public void gets() throws Exception { assertThat(full.gets()).isEqualTo("Hello,\n".getBytes()); } @Test public void getsWithCrLf() throws Exception { assertThat(rackInputFor("Hello,\r\nWorld!").gets()).isEqualTo("Hello,\r\n".getBytes()); } @Test public void getsAgain() throws Exception { full.gets(); assertThat(full.gets()).isEqualTo("World!".getBytes()); } @Test public void readWithLengthNilAtEof() throws Exception { assertThat(empty.read(null)).isEqualTo(EMPTY_BYTES); } @Test public void readWithLengthZeroAtEof() throws Exception { assertThat(empty.read(0)).isEqualTo(EMPTY_BYTES); } @Test public void readWithLengthAtEof() throws Exception { assertThat(empty.read(1)).isNull(); } @Test public void readWithLengthNil() throws Exception { assertThat(full.read(null)).isEqualTo(BYTES); } @Test public void readWithLengthNilAgain() throws Exception { full.read(null); assertThat(full.read(null)).isEqualTo(EMPTY_BYTES); } @Test public void readWithLengthZero() throws Exception { assertThat(full.read(0)).isEqualTo(EMPTY_BYTES); } @Test public void readWithLength() throws Exception { assertThat(full.read(4)).isEqualTo(copyOfRange(BYTES, 0, 4)); } @Test public void readWithLengthAgain() throws Exception { full.read(4); assertThat(full.read(4)).isEqualTo(copyOfRange(BYTES, 4, 8)); } @Test public void readFromSlowStreamWithLength() throws Exception { assertThat(fullSlow.read(4)).isEqualTo(copyOfRange(BYTES, 0, 4)); } @Test public void readFromSlowStreamWithLengthAgain() throws Exception { fullSlow.read(4); assertThat(fullSlow.read(4)).isEqualTo(copyOfRange(BYTES, 4, 8)); } @Test public void readWithLengthTooLong() throws Exception { assertThat(full.read(BYTES.length + 1)).isEqualTo(BYTES); } @Test public void readWithLengthTooLongAgain() throws Exception { full.read(BYTES.length + 1); assertThat(full.read(BYTES.length + 1)).isNull(); } @Test public void rewind() throws Exception { full.read(4); full.rewind(); assertThat(full.read(4)).isEqualTo(copyOfRange(BYTES, 0, 4)); } @Test public void rewind_shouldDiscardAnyBufferedBytes() throws Exception { RackInput subject = rackInputFor("first line\r\n123\r\n456\r\n"); subject.gets(); subject.rewind(); assertThat(subject.gets()).isEqualTo("first line\r\n".getBytes()); assertThat(subject.gets()).isEqualTo("123\r\n".getBytes()); } @Test public void intermixingReadMethodsIsSafe() throws Exception { RackInput subject = rackInputFor("first line\r\n123\r\n456\r\n"); assertThat(subject.read(1)).isEqualTo("f".getBytes()); assertThat(subject.gets()).isEqualTo("irst line\r\n".getBytes()); assertThat(subject.read(null)).isEqualTo("123\r\n456\r\n".getBytes()); subject.rewind(); assertThat(subject.gets()).isEqualTo("first line\r\n".getBytes()); assertThat(subject.read(3)).isEqualTo("123".getBytes()); assertThat(subject.gets()).isEqualTo("\r\n".getBytes()); assertThat(subject.read(null)).isEqualTo("456\r\n".getBytes()); } private RackInput rackInputFor(String string) throws Exception { return rackInputFor(string.getBytes()); } private RackInput rackInputFor(byte[] bytes) throws Exception { return new RackInput(new ByteArrayInputStream(bytes)); } private RackInput slowRackInputFor(byte[] bytes) throws Exception { return new RackInput(new SlowByteArrayInputStream(bytes)); } }
5,579
0
Create_ds/rack-servlet/core/src/test/java/com/squareup
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/RackLoggerTest.java
package com.squareup.rack; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.Logger; import static com.squareup.rack.RackLogger.FATAL; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class RackLoggerTest { private static final String MESSAGE = "message"; private RackLogger subject; @Mock private Logger delegate; @Before public void setUp() { subject = new RackLogger(delegate); } @Test(expected = NullPointerException.class) public void constructorRequiresALogger() { new RackLogger(null); } @Test public void info() { subject.info(MESSAGE); verify(delegate).info(MESSAGE); } @Test public void debug() { subject.debug(MESSAGE); verify(delegate).debug(MESSAGE); } @Test public void warn() { subject.warn(MESSAGE); verify(delegate).warn(MESSAGE); } @Test public void error() { subject.error(MESSAGE); verify(delegate).error(MESSAGE); } @Test public void fatal() { subject.fatal(MESSAGE); verify(delegate).error(FATAL, MESSAGE); } }
5,580
0
Create_ds/rack-servlet/core/src/test/java/com/squareup
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/RackErrorsTest.java
package com.squareup.rack; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.Logger; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class RackErrorsTest { private RackErrors rackErrors; @Mock private Logger logger; @Before public void setUp() { rackErrors = new RackErrors(logger); } @Test(expected = NullPointerException.class) public void constructorRequiresALogger() { new RackErrors(null); } @Test public void puts() { rackErrors.puts("Boom!"); verify(logger).error("Boom!"); } @Test public void write() { rackErrors.write("Boom?"); verify(logger, never()).error(anyString()); } @Test public void writeThenFlush() { rackErrors.write("Boom?"); rackErrors.flush(); verify(logger).error("Boom?"); } @Test public void writeWriteWriteThenFlush() { rackErrors.write("Boom?"); rackErrors.write("Boom!"); rackErrors.write("Boom…"); rackErrors.flush(); verify(logger).error("Boom?Boom!Boom…"); } @Test public void flushOnEmpty() { rackErrors.flush(); verify(logger, never()).error(anyString()); } @Test public void writeFlushWriteFlush() { rackErrors.write("A loooong message"); rackErrors.flush(); rackErrors.write("A short msg"); rackErrors.flush(); InOrder inOrder = inOrder(logger); inOrder.verify(logger).error("A loooong message"); inOrder.verify(logger).error("A short msg"); } }
5,581
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/servlet/RackResponsePropagatorTest.java
package com.squareup.rack.servlet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.squareup.rack.RackResponse; import java.io.IOException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class RackResponsePropagatorTest { private RackResponsePropagator subject; private RackResponseBuilder rackResponse; @Mock private HttpServletResponse response; @Mock private ServletOutputStream outputStream; @Before public void setUp() throws IOException { subject = new RackResponsePropagator(); rackResponse = new RackResponseBuilder(); when(response.getOutputStream()).thenReturn(outputStream); } @Test public void propagateStatus() { rackResponse.status(404); subject.propagate(rackResponse.build(), response); verify(response).setStatus(404); } @Test public void propagateHeaders() { rackResponse.header("Content-Type", "text/plain"); subject.propagate(rackResponse.build(), response); verify(response).addHeader("Content-Type", "text/plain"); } @Test public void propagateHeadersSkipsHeadsRackHeaders() { rackResponse.header("rack.internal", "42"); subject.propagate(rackResponse.build(), response); verify(response, never()).addHeader(eq("rack.internal"), anyString()); } @Test public void propagateHeadersMultipleValues() { rackResponse.header("Set-Cookie", "foo=bar\nbar=foo"); subject.propagate(rackResponse.build(), response); verify(response).addHeader("Set-Cookie", "foo=bar"); verify(response).addHeader("Set-Cookie", "bar=foo"); } @Test public void propagateBody() throws IOException { rackResponse.body("Here ".getBytes(), "are ".getBytes(), "the ".getBytes(), "parts.".getBytes()); subject.propagate(rackResponse.build(), response); InOrder inOrder = inOrder(outputStream); inOrder.verify(outputStream).write("Here ".getBytes()); inOrder.verify(outputStream).write("are ".getBytes()); inOrder.verify(outputStream).write("the ".getBytes()); inOrder.verify(outputStream).write("parts.".getBytes()); inOrder.verify(outputStream).flush(); } private static class RackResponseBuilder { private int status; private final ImmutableMap.Builder<String, String> headers; private final ImmutableList.Builder<byte[]> body; public RackResponseBuilder() { this.status = 200; this.headers = ImmutableMap.builder(); this.body = ImmutableList.builder(); } public RackResponseBuilder status(int status) { this.status = status; return this; } public RackResponseBuilder header(String key, String value) { this.headers.put(key, value); return this; } public RackResponseBuilder body(byte[]... parts) { body.add(parts); return this; } public RackResponse build() { return new RackResponse(status, headers.build(), body.build().iterator()); } } }
5,582
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/servlet/TestHttpServletRequest.java
package com.squareup.rack.servlet; import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ListMultimap; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletInputStream; import static com.google.common.base.Strings.emptyToNull; public class TestHttpServletRequest extends NullHttpServletRequest { private final String method; private final String servletPath; private final URI uri; private final ListMultimap<String, String> headers; private final String body; private final Map<String, Object> attributes; public static Builder newBuilder() { return new Builder(); } public static class Builder { private final HashMap<String, Object> attributes; private String method; private String servletPath; private URI requestUri; private ImmutableListMultimap.Builder<String, String> headersBuilder; private String body; private Builder() { method = "GET"; servletPath = ""; requestUri = URI.create("http://example.com/"); headersBuilder = ImmutableListMultimap.builder(); body = ""; attributes = new HashMap<String, Object>(); } public Builder body(String body) { this.body = body; return this; } public Builder method(String method) { this.method = method; return this; } private static final CharMatcher SLASH = CharMatcher.is('/'); private static final CharMatcher STAR = CharMatcher.is('*'); public Builder whenMountedAt(String path) { this.servletPath = SLASH.trimTrailingFrom(STAR.trimTrailingFrom(path)); return this; } public Builder header(String key, String value) { headersBuilder.put(key, value); return this; } public Builder uri(String uri) { this.requestUri = URI.create(uri); return this; } public Builder attribute(String name, Object value) { attributes.put(name, value); return this; } public TestHttpServletRequest build() { return new TestHttpServletRequest(method, servletPath, requestUri, headersBuilder.build(), body, attributes); } } private TestHttpServletRequest(String method, String servletPath, URI uri, ListMultimap<String, String> headers, String body, Map<String, Object> attributes) { this.method = method; this.servletPath = servletPath; this.uri = uri; this.headers = headers; this.body = body; this.attributes = attributes; } @Override public String getMethod() { return method; } @Override public String getServletPath() { return servletPath; } @Override public String getPathInfo() { return emptyToNull(uri.getPath().substring(servletPath.length())); } @Override public String getQueryString() { return uri.getQuery(); } @Override public String getServerName() { return uri.getHost(); } @Override public int getServerPort() { int port = uri.getPort(); String scheme = uri.getScheme(); return (port > 0) ? port : (scheme.equals("https") ? 443 : 80); } @Override public String getScheme() { return uri.getScheme(); } @Override public ServletInputStream getInputStream() throws IOException { final InputStream stream = new ByteArrayInputStream(body.getBytes()); return new ServletInputStream() { @Override public int read() throws IOException { return stream.read(); } }; } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(headers.keySet()); } @Override public Enumeration<String> getHeaders(String name) { return Collections.enumeration(headers.get(name)); } @Override public Object getAttribute(String name) { return attributes.get(name); } @Override public Enumeration<String> getAttributeNames() { final Iterator<String> iterator = attributes.keySet().iterator(); return new Enumeration<String>() { public boolean hasMoreElements() { return iterator.hasNext(); } public String nextElement() { return iterator.next(); } }; } }
5,583
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/servlet/TestHttpServletRequestTest.java
package com.squareup.rack.servlet; import org.junit.Before; import org.junit.Test; import static java.lang.String.format; import static org.fest.assertions.api.Assertions.assertThat; // Examples taken from http://account.pacip.com/jetty/doc/PathMapping.html public class TestHttpServletRequestTest { private TestHttpServletRequest.Builder builder; @Before public void setUp() { builder = TestHttpServletRequest.newBuilder(); } @Test public void absoluteMapping() { mount("/path"); assertThat(get("/path").getServletPath()).isEqualTo("/path"); assertThat(get("/path").getPathInfo()).isNull(); } @Test public void prefixMapping_bare() { mount("/path/*"); assertThat(get("/path").getServletPath()).isEqualTo("/path"); assertThat(get("/path").getPathInfo()).isNull(); } @Test public void prefixMapping_slash() { mount("/path/*"); assertThat(get("/path/").getServletPath()).isEqualTo("/path"); assertThat(get("/path/").getPathInfo()).isEqualTo("/"); } @Test public void prefixMapping_slashPath() { mount("/path/*"); assertThat(get("/path/info").getServletPath()).isEqualTo("/path"); assertThat(get("/path/info").getPathInfo()).isEqualTo("/info"); } @Test public void defaultMapping_slash() { mount("/"); assertThat(get("/").getServletPath()).isEqualTo(""); assertThat(get("/").getPathInfo()).isEqualTo("/"); } @Test public void defaultMapping_slashPath() { mount("/"); assertThat(get("/path").getServletPath()).isEqualTo(""); assertThat(get("/path").getPathInfo()).isEqualTo("/path"); } @Test public void defaultMapping_slashPathSlash() { mount("/"); assertThat(get("/path/").getServletPath()).isEqualTo(""); assertThat(get("/path/").getPathInfo()).isEqualTo("/path/"); } @Test public void defaultMapping_slashPathSlashPath() { mount("/"); assertThat(get("/path/info").getServletPath()).isEqualTo(""); assertThat(get("/path/info").getPathInfo()).isEqualTo("/path/info"); } private TestHttpServletRequest.Builder mount(String mountPath) { return builder.whenMountedAt(mountPath); } private TestHttpServletRequest get(String requestPath) { return builder.uri(format("%s%s", "http://example.com", requestPath)).build(); } }
5,584
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/servlet/RackServletTest.java
package com.squareup.rack.servlet; import com.squareup.rack.RackApplication; import com.squareup.rack.RackEnvironment; import com.squareup.rack.RackResponse; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class RackServletTest { private RackServlet subject; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private RackApplication rackApplication; @Mock private RackEnvironmentBuilder rackEnvironmentBuilder; @Mock private RackEnvironment rackEnvironment; @Mock private RackResponse rackResponse; @Mock private RackResponsePropagator rackResponsePropagator; @Before public void setUp() { subject = new RackServlet(rackEnvironmentBuilder, rackApplication, rackResponsePropagator); when(rackEnvironmentBuilder.build(request)).thenReturn(rackEnvironment); } @Test public void service() throws ServletException, IOException { when(rackApplication.call(rackEnvironment)).thenReturn(rackResponse); subject.service(request, response); InOrder inOrder = inOrder(rackResponsePropagator, rackEnvironment); inOrder.verify(rackResponsePropagator).propagate(rackResponse, response); inOrder.verify(rackEnvironment).closeRackInput(); } }
5,585
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/servlet/RackEnvironmentBuilderTest.java
package com.squareup.rack.servlet; import com.google.common.collect.ImmutableList; import com.squareup.rack.RackErrors; import com.squareup.rack.RackInput; import com.squareup.rack.RackLogger; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.data.MapEntry.entry; @RunWith(MockitoJUnitRunner.class) public class RackEnvironmentBuilderTest { private TestHttpServletRequest.Builder request; private HttpServletRequest httpServletRequest; @Before public void setUp() { this.request = TestHttpServletRequest.newBuilder(); } @Test public void requestMethod() { request.method("PUT"); assertThat(environment()).contains(entry("REQUEST_METHOD", "PUT")); } @Test public void scriptNameAndPathInfoWheRequestingTheRoot() { request.uri("http://example.com/"); assertThat(environment()).contains(entry("SCRIPT_NAME", "")); assertThat(environment()).contains(entry("PATH_INFO", "/")); } @Test public void scriptNameAndPathInfoWhenRequestingAPath() { request.uri("http://example.com/path/to/resource"); assertThat(environment()).contains(entry("SCRIPT_NAME", "")); assertThat(environment()).contains(entry("PATH_INFO", "/path/to/resource")); } @Test public void scriptNameAndPathInfoWhenMountedAndRequestingTheRoot() { request.uri("http://example.com/path/to").whenMountedAt("/path/to/*"); assertThat(environment()).contains(entry("SCRIPT_NAME", "/path/to")); assertThat(environment()).contains(entry("PATH_INFO", "")); } @Test public void scriptNameAndPathInfoWhenMountedAndRequestingAPath() { request.uri("http://example.com/path/to/resource").whenMountedAt("/path/to/*"); assertThat(environment()).contains(entry("SCRIPT_NAME", "/path/to")); assertThat(environment()).contains(entry("PATH_INFO", "/resource")); } @Test public void queryString() { request.uri("http://example.com/"); assertThat(environment()).contains(entry("QUERY_STRING", "")); } @Test public void queryStringGiven() { request.uri("http://example.com/?foo=bar"); assertThat(environment()).contains(entry("QUERY_STRING", "foo=bar")); } @Test public void serverName() { request.uri("http://example.com/"); assertThat(environment()).contains(entry("SERVER_NAME", "example.com")); } @Test public void serverPortHttp() { request.uri("http://example.com/"); assertThat(environment()).contains(entry("SERVER_PORT", "80")); } @Test public void serverPortHttps() { request.uri("https://example.com/"); assertThat(environment()).contains(entry("SERVER_PORT", "443")); } @Test public void serverPortGiven() { request.uri("http://example.com:1234/"); assertThat(environment()).contains(entry("SERVER_PORT", "1234")); } @Test public void httpHeaders() { request.header("If-None-Match", "737060cd8c284d8af7ad3082f209582d"); assertThat(environment()).contains( entry("HTTP_IF_NONE_MATCH", "737060cd8c284d8af7ad3082f209582d")); } @Test public void httpHeadersWithMultipleValues() { request.header("Accept", "text/plain").header("Accept", "text/html"); assertThat(environment()).contains(entry("HTTP_ACCEPT", "text/plain,text/html")); } @Test public void httpHeadersContentLength() { request.header("Content-Length", "42"); assertThat(environment()).contains(entry("CONTENT_LENGTH", "42")); assertThat(environment()).doesNotContainKey("HTTP_CONTENT_LENGTH"); } @Test public void httpHeadersContentType() { request.header("Content-Type", "application/json"); assertThat(environment()).contains(entry("CONTENT_TYPE", "application/json")); assertThat(environment()).doesNotContainKey("HTTP_CONTENT_TYPE"); } @Test public void httpHeadersXForwardedForMultiple() { request.header("X-Forwarded-For", "192.168.0.1"); request.header("X-Forwarded-For", "10.0.1.1"); assertThat(environment()).contains(entry("HTTP_X_FORWARDED_FOR", "192.168.0.1,10.0.1.1")); } @Test public void httpHeadersXForwardedForMultiplePunctuationDifferences() { // There seems to be mixed consensus on the internet as to what to do in this case. Underscores // are perfectly valid in HTTP header names, but many webservers discard such headers so as to // avoid collision with CGI environment variables. (See nginx's underscores_in_headers setting.) // We choose to honor them, folding their values in with their dashed brethren. request.header("X-Forwarded-For", "192.168.0.1"); request.header("X-Forwarded_For", "10.0.1.1"); assertThat(environment()).contains(entry("HTTP_X_FORWARDED_FOR", "192.168.0.1,10.0.1.1")); } @Test public void rackVersion() { assertThat(environment()).contains(entry("rack.version", ImmutableList.of(1, 2))); } @Test public void rackUrlSchemeHttp() { request.uri("http://example.com/"); assertThat(environment()).contains(entry("rack.url_scheme", "http")); } @Test public void rackUrlSchemeHttps() { request.uri("https://example.com/"); assertThat(environment()).contains(entry("rack.url_scheme", "https")); } @Test public void rackUrlSchemeHttpYelling() { request.uri("HTTP://EXAMPLE.COM/"); assertThat(environment()).contains(entry("rack.url_scheme", "http")); } @Test public void rackInput() throws IOException { request.method("POST").body("foo=42&bar=0"); assertThat(environment()).containsKey("rack.input"); assertThat(environment().get("rack.input")).isInstanceOf(RackInput.class); } @Test public void rackErrors() { assertThat(environment()).containsKey("rack.errors"); assertThat(environment().get("rack.errors")).isInstanceOf(RackErrors.class); } @Test public void rackLogger() { assertThat(environment()).containsKey("rack.logger"); assertThat(environment().get("rack.logger")).isInstanceOf(RackLogger.class); } @Test public void rackMultithread() { assertThat(environment()).contains(entry("rack.multithread", true)); } @Test public void rackMultiprocess() { assertThat(environment()).contains(entry("rack.multiprocess", true)); } @Test public void rackRunOnce() { assertThat(environment()).contains(entry("rack.run_once", false)); } @Test public void rackIsHijack() { assertThat(environment()).contains(entry("rack.hijack?", false)); } @Test public void rackHijack() { assertThat(environment()).doesNotContainKey("rack.hijack"); } @Test public void rackHijackIo() { assertThat(environment()).doesNotContainKey("rack.hijack_io"); } @Test public void rackHttpServletRequest() { assertThat(environment()).containsKey("minecart.http_servlet_request"); assertThat(environment().get("minecart.http_servlet_request")).isSameAs(httpServletRequest); } @Test public void rackAttributes() { Object testObject = new Object(); request.attribute("ExampleAttribute", testObject); assertThat(environment()).containsKey("ExampleAttribute"); assertThat(environment().get("ExampleAttribute")).isSameAs(testObject); } private Map<String, Object> environment() { RackEnvironmentBuilder environmentBuilder = new RackEnvironmentBuilder(); httpServletRequest = request.build(); return environmentBuilder.build(httpServletRequest); } }
5,586
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/servlet/NullHttpServletRequest.java
package com.squareup.rack.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; class NullHttpServletRequest implements HttpServletRequest { @Override public String getAuthType() { return null; } @Override public Cookie[] getCookies() { return new Cookie[0]; } @Override public long getDateHeader(String name) { return 0; } @Override public String getHeader(String name) { return null; } @Override public Enumeration<String> getHeaders(String name) { return null; } @Override public Enumeration<String> getHeaderNames() { return null; } @Override public int getIntHeader(String name) { return 0; } @Override public String getMethod() { return null; } @Override public String getPathInfo() { return null; } @Override public String getPathTranslated() { return null; } @Override public String getContextPath() { return null; } @Override public String getQueryString() { return null; } @Override public String getRemoteUser() { return null; } @Override public boolean isUserInRole(String role) { return false; } @Override public Principal getUserPrincipal() { return null; } @Override public String getRequestedSessionId() { return null; } @Override public String getRequestURI() { return null; } @Override public StringBuffer getRequestURL() { return null; } @Override public String getServletPath() { return null; } @Override public HttpSession getSession(boolean create) { return null; } @Override public HttpSession getSession() { return null; } @Override public boolean isRequestedSessionIdValid() { return false; } @Override public boolean isRequestedSessionIdFromCookie() { return false; } @Override public boolean isRequestedSessionIdFromURL() { return false; } @Override public boolean isRequestedSessionIdFromUrl() { return false; } @Override public Object getAttribute(String name) { return null; } @Override public Enumeration<String> getAttributeNames() { return null; } @Override public String getCharacterEncoding() { return null; } @Override public void setCharacterEncoding(String env) throws UnsupportedEncodingException { } @Override public int getContentLength() { return 0; } @Override public String getContentType() { return null; } @Override public ServletInputStream getInputStream() throws IOException { return null; } @Override public String getParameter(String name) { return null; } @Override public Enumeration<String> getParameterNames() { return null; } @Override public String[] getParameterValues(String name) { return new String[0]; } @Override public Map<String, String[]> getParameterMap() { return null; } @Override public String getProtocol() { return null; } @Override public String getScheme() { return null; } @Override public String getServerName() { return null; } @Override public int getServerPort() { return 0; } @Override public BufferedReader getReader() throws IOException { return null; } @Override public String getRemoteAddr() { return null; } @Override public String getRemoteHost() { return null; } @Override public void setAttribute(String name, Object o) { } @Override public void removeAttribute(String name) { } @Override public Locale getLocale() { return null; } @Override public Enumeration<Locale> getLocales() { return null; } @Override public boolean isSecure() { return false; } @Override public RequestDispatcher getRequestDispatcher(String path) { return null; } @Override public String getRealPath(String path) { return null; } @Override public int getRemotePort() { return 0; } @Override public String getLocalName() { return null; } @Override public String getLocalAddr() { return null; } @Override public int getLocalPort() { return 0; } }
5,587
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/io/TempfileBufferedInputStreamTest.java
package com.squareup.rack.io; import com.google.common.io.CharStreams; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.fest.assertions.api.Assertions.assertThat; public class TempfileBufferedInputStreamTest { public @Rule TemporaryFolder tempDir = new TemporaryFolder(); @Test public void readingAShortStreamTwice() throws IOException { InputStream subject = new TempfileBufferedInputStream(containing("Hello!")); subject.mark(10); assertThat(read(subject)).isEqualTo("Hello!"); subject.reset(); assertThat(read(subject)).isEqualTo("Hello!"); } @Test public void readingALongStreamTwice() throws IOException { InputStream subject = new TempfileBufferedInputStream(containing("Hello!"), 3); subject.mark(10); assertThat(read(subject)).isEqualTo("Hello!"); subject.reset(); assertThat(read(subject)).isEqualTo("Hello!"); } @Test public void shouldResetToMarkUnderThreshold() throws Exception { InputStream subject = new TempfileBufferedInputStream(containing("Hello!")); read(subject, 2); subject.mark(10); read(subject); subject.reset(); assertThat(read(subject)).isEqualTo("llo!"); } @Test public void shouldResetToMarkOverThreshold() throws Exception { InputStream subject = new TempfileBufferedInputStream(containing("Hello!"), 3); read(subject, 4); subject.mark(10); read(subject); subject.reset(); assertThat(read(subject)).isEqualTo("o!"); } @Test public void shouldSupportMultipleMarks() throws Exception { InputStream subject = new TempfileBufferedInputStream(containing("123456789"), 3); subject.mark(10); // set the mark at '1' read(subject, 4); subject.reset(); read(subject, 4); subject.mark(10); // move the mark to '5' read(subject, 1); assertThat(read(subject)).isEqualTo("6789"); subject.reset(); assertThat(read(subject)).isEqualTo("56789"); } @Test public void shouldNotLeaveTempFilesLingering() throws Exception { String originalTmpdir = System.getProperty("java.io.tmpdir"); System.setProperty("java.io.tmpdir", tempDir.getRoot().toString()); try { InputStream subject = new TempfileBufferedInputStream(containing("123456789"), 3); read(subject); assertThat(tempDir.getRoot().listFiles()).isEmpty(); } finally { System.setProperty("java.io.tmpdir", originalTmpdir); } } @Test public void whenClosed_shouldCloseSourceStream() throws Exception { final List<String> log = new ArrayList<String>(); InputStream source = new ByteArrayInputStream("bytes".getBytes()) { @Override public void close() throws IOException { log.add("closed InputStream"); super.close(); } }; InputStream subject = new TempfileBufferedInputStream(source, 3); read(subject); subject.close(); assertThat(log).contains("closed InputStream"); } @Test public void whenClosed_shouldCloseTempFileStreamsIgnoringExceptions() throws Exception { final List<String> log = new ArrayList<String>(); InputStream subject = new TempfileBufferedInputStream(containing("123456789"), 3) { @Override FileInputStream createFileInputStream(File tempFile) throws FileNotFoundException { return new FileInputStream(tempFile) { @Override public void close() throws IOException { log.add("closed FileInputStream"); throw new IOException("fake exception"); } }; } @Override FileOutputStream createFileOutputStream(File tempFile) throws FileNotFoundException { return new FileOutputStream(tempFile) { @Override public void close() throws IOException { log.add("closed FileOutputStream"); throw new IOException("fake exception"); } }; } }; read(subject); subject.close(); assertThat(log).contains("closed FileInputStream", "closed FileOutputStream"); } private ByteArrayInputStream containing(String content) { return new ByteArrayInputStream(content.getBytes()); } private String read(InputStream subject) throws IOException { return CharStreams.toString(new InputStreamReader(subject)); } private void read(InputStream subject, int count) throws IOException { subject.read(new byte[count], 0, count); } }
5,588
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/jruby/JRubyRackApplicationTest.java
package com.squareup.rack.jruby; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.squareup.rack.RackApplication; import com.squareup.rack.RackEnvironment; import com.squareup.rack.RackResponse; import com.squareup.rack.servlet.RackEnvironmentBuilder; import com.squareup.rack.servlet.TestHttpServletRequest; import java.util.Iterator; import org.jruby.Ruby; import org.jruby.runtime.builtin.IRubyObject; import org.junit.Before; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.data.MapEntry.entry; public class JRubyRackApplicationTest { private static final Joiner SPACE = Joiner.on(' '); private RackApplication app; private RackEnvironment env; @Before public void setUp() { IRubyObject callable = Ruby.getGlobalRuntime() .evalScriptlet("proc { |env| [200, {'Content-Type' => 'text/plain'}, env.keys] }"); RackEnvironmentBuilder envBuilder = new RackEnvironmentBuilder(); TestHttpServletRequest request = TestHttpServletRequest.newBuilder().build(); app = new JRubyRackApplication(callable); env = envBuilder.build(request); } @Test public void callSetsTheResponseStatus() { RackResponse response = app.call(env); assertThat(response.getStatus()).isEqualTo(200); } @Test public void callSetsTheResponseHeaders() { RackResponse response = app.call(env); assertThat(response.getHeaders()).contains(entry("Content-Type", "text/plain")); } @Test public void callSetsTheResponseBody() { RackResponse response = app.call(env); ImmutableList.Builder<String> strings = ImmutableList.builder(); Iterator<byte[]> bytes = response.getBody(); while (bytes.hasNext()) { strings.add(new String(bytes.next())); } assertThat(SPACE.join(strings.build())).isEqualTo(SPACE.join(env.keySet())); } @Test public void callParsesTheResponseStatusFromAString() { IRubyObject callable = Ruby.getGlobalRuntime() .evalScriptlet("proc { |env| ['201', {'Content-Type' => 'text/plain'}, env.keys] }"); app = new JRubyRackApplication(callable); RackResponse response = app.call(env); assertThat(response.getStatus()).isEqualTo(201); } }
5,589
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/jruby/JRubyRackInputTest.java
package com.squareup.rack.jruby; import com.squareup.rack.RackInput; import java.io.IOException; import org.jruby.Ruby; import org.jruby.internal.runtime.GlobalVariables; import org.jruby.runtime.builtin.IRubyObject; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JRubyRackInputTest { @Test public void shouldWrapJavaIOExceptions() throws Exception { Ruby ruby = Ruby.newInstance(); RackInput rackInput = mock(RackInput.class); when(rackInput.read(null)).thenThrow(new IOException("fake")); JRubyRackInput subject = new JRubyRackInput(ruby, rackInput); GlobalVariables globalVariables = ruby.getGlobalVariables(); globalVariables.set("$rack_input", subject); IRubyObject result = ruby.evalScriptlet( "begin; $rack_input.read; rescue IOError => e; \"rescued #{e.message}\"; end"); assertThat(result.asJavaString()).isEqualTo("rescued fake"); } }
5,590
0
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack
Create_ds/rack-servlet/core/src/test/java/com/squareup/rack/jruby/JRubyRackBodyIteratorTest.java
package com.squareup.rack.jruby; import org.jruby.embed.PathType; import org.jruby.embed.ScriptingContainer; import org.jruby.runtime.builtin.IRubyObject; import org.junit.Before; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class JRubyRackBodyIteratorTest { private ScriptingContainer scriptingContainer; @Before public void setUp() { scriptingContainer = new ScriptingContainer(); scriptingContainer.runScriptlet(PathType.CLASSPATH, "enumerable_with_close.rb"); } @Test public void iteratingOverAThingThatRespondsToClose_shouldCloseTheThing() { IRubyObject body = scriptingContainer.parse("EnumerableWithClose.new(%w(first second third))").run(); JRubyRackBodyIterator subject = new JRubyRackBodyIterator(body); assertThat(isOpen(body)).isEqualTo(true); while (subject.hasNext()) { subject.next(); } assertThat(isOpen(body)).isEqualTo(false); } @Test public void iteratingOverAThingThatDoesNotRespondToClose_shouldNotBlowUp() { JRubyRackBodyIterator subject = new JRubyRackBodyIterator( scriptingContainer.parse("%w(first second third)").run()); while (subject.hasNext()) { subject.next(); } } private Boolean isOpen(IRubyObject body) { return (Boolean) body.callMethod(body.getRuntime().getCurrentContext(), "open").toJava(Boolean.class); } }
5,591
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/RackErrors.java
/* * Copyright (C) 2013 Square, 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.squareup.rack; import org.slf4j.Logger; import static com.google.common.base.Preconditions.checkNotNull; /** * Adapts a {@link Logger} to the required interface for {@code rack.errors}. */ public class RackErrors { private final Logger logger; private final StringBuffer buffer; /** * Creates a {@link RackErrors} stream that forwards messages to the given {@link Logger}. * * @param logger the destination {@link Logger}. */ public RackErrors(Logger logger) { this.logger = checkNotNull(logger); this.buffer = new StringBuffer(); } /** * Immediately writes the given message out to the error logger. * * @param message */ public void puts(String message) { logger.error(message); } /** * Buffers the given message internally. You may call {@link #write(String)} as many times as you * like. To then write the composite buffered message to the error logger, call {@link #flush()}. * * @param message */ public void write(String message) { buffer.append(message); } /** * Writes internally-buffered messages out to the error logger. * * @see #write(String) */ public void flush() { if (buffer.length() > 0) { logger.error(buffer.toString()); buffer.setLength(0); } } }
5,592
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/RackResponse.java
/* * Copyright (C) 2013 Square, 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.squareup.rack; import java.util.Iterator; import java.util.Map; /** * The HTTP response generated by a {@link RackApplication}. */ public class RackResponse { private final int status; private final Map<String, String> headers; private final Iterator<byte[]> body; /** * Creates a {@link RackResponse} with the given contents. * * @param status the HTTP status code. * @param headers the HTTP response headers. * @param body the HTTP response body. */ public RackResponse(int status, Map<String, String> headers, Iterator<byte[]> body) { this.status = status; this.headers = headers; this.body = body; } /** * @return the HTTP status code. */ public int getStatus() { return status; } /** * @return the HTTP response headers. */ public Map<String, String> getHeaders() { return headers; } /** * @return the HTTP response body. */ public Iterator<byte[]> getBody() { return body; } }
5,593
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/RackLogger.java
/* * Copyright (C) 2013 Square, 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.squareup.rack; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import static com.google.common.base.Preconditions.checkNotNull; /** * Adapts a {@link Logger} to the required interface for {@code rack.logger}. */ public class RackLogger { public static final Marker FATAL = MarkerFactory.getMarker("FATAL"); private final Logger logger; /** * Creates a {@link RackLogger} that forwards messages to the given {@link Logger}. * * @param logger */ public RackLogger(Logger logger) { this.logger = checkNotNull(logger); } public void info(String message) { logger.info(message); } public void debug(String message) { logger.debug(message); } public void warn(String message) { logger.warn(message); } public void error(String message) { logger.error(message); } public void fatal(String message) { // See http://www.slf4j.org/faq.html#fatal logger.error(FATAL, message); } }
5,594
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/RackApplication.java
/* * Copyright (C) 2013 Square, 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.squareup.rack; /** * A Rack application. * * @see <a href="http://rack.rubyforge.org/doc/SPEC.html">The Rack Specification</a> */ public interface RackApplication { /** * Processes a single HTTP request. * * @param environment the HTTP request environment. * @return the HTTP response. */ RackResponse call(RackEnvironment environment); }
5,595
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/RackEnvironment.java
/* * Copyright (C) 2013 Square, 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.squareup.rack; import com.google.common.collect.ForwardingMap; import java.io.Closeable; import java.io.IOException; import java.util.Map; /** * The HTTP request environment consumed by a {@link RackApplication}. * * @see <a href="http://rack.rubyforge.org/doc/SPEC.html">The Rack Specification</a> * @see com.squareup.rack.servlet.RackEnvironmentBuilder */ public class RackEnvironment extends ForwardingMap<String, Object> { public static final String REQUEST_METHOD = "REQUEST_METHOD"; public static final String SCRIPT_NAME = "SCRIPT_NAME"; public static final String PATH_INFO = "PATH_INFO"; public static final String QUERY_STRING = "QUERY_STRING"; public static final String SERVER_NAME = "SERVER_NAME"; public static final String SERVER_PORT = "SERVER_PORT"; public static final String CONTENT_LENGTH = "CONTENT_LENGTH"; public static final String CONTENT_TYPE = "CONTENT_TYPE"; public static final String HTTP_HEADER_PREFIX = "HTTP_"; public static final String RACK_VERSION = "rack.version"; public static final String RACK_URL_SCHEME = "rack.url_scheme"; public static final String RACK_INPUT = "rack.input"; public static final String RACK_ERRORS = "rack.errors"; public static final String RACK_LOGGER = "rack.logger"; public static final String RACK_MULTITHREAD = "rack.multithread"; public static final String RACK_MULTIPROCESS = "rack.multiprocess"; public static final String RACK_RUN_ONCE = "rack.run_once"; public static final String RACK_HIJACK = "rack.hijack?"; public static final String MINECART_HTTP_SERVLET_REQUEST = "minecart.http_servlet_request"; private final Map<String, Object> contents; /** * Creates a {@link RackEnvironment} with the given contents. * * @see com.squareup.rack.servlet.RackEnvironmentBuilder * @param contents */ public RackEnvironment(Map<String, Object> contents) { this.contents = contents; } /** * Closes the rack.input stream. * * @throws IOException */ public void closeRackInput() throws IOException { ((Closeable) contents.get(RACK_INPUT)).close(); } @Override protected Map<String, Object> delegate() { return contents; } }
5,596
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/RackInput.java
/* * Copyright (C) 2013 Square, 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.squareup.rack; import com.google.common.io.ByteStreams; import com.squareup.rack.io.ByteArrayBuffer; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * <p>Adapts an {@link InputStream} to the required interface for {@code rack.input}.</p> * * <p>Speaks {@code byte[]}, not {@code String}, because {@code rack.input} is required to have * binary encoding.</p> */ public class RackInput implements Closeable { private static final int LINEFEED = 0xA; private static final int MAX_LINE_LENGTH = 1024 * 1024; private static final int READ_AHEAD_SUGGESTION = 1024 * 1024; private final InputStream stream; private final ByteArrayBuffer buffer = new ByteArrayBuffer(); private int bufferReadHead; /** * Creates a {@link RackInput} stream that draws from the given {@link InputStream}. * * @param inputStream the source stream. */ public RackInput(InputStream inputStream) { checkNotNull(inputStream); checkArgument(inputStream.markSupported(), "rack.input must be rewindable, but inputStream doesn't support mark."); stream = inputStream; stream.mark(READ_AHEAD_SUGGESTION); } /** * Reads the next line from the stream. * * @return the next line, or null at EOF. * @throws IOException */ public byte[] gets() throws IOException { return readToLinefeed(); } /** * Reads length bytes from the stream. Reads all the way to EOF when length is null. * * @param length the desired number of bytes, or null. * @return the bytes, or null at EOF when length is present. * @throws IOException */ public byte[] read(Integer length) throws IOException { if (length == null) { return readToEof(); } else { return readTo(length); } } /** * Resets the stream, so that it may be read again from the beginning. * * @throws IOException */ public void rewind() throws IOException { stream.reset(); buffer.reset(); bufferReadHead = 0; } /** * Closes the stream. * * @throws IOException */ @Override public void close() throws IOException { stream.close(); } private byte[] readToLinefeed() throws IOException { int startFrom = 0; do { int indexOfNewline = indexOfNextNewlineInBuffer(startFrom); if (indexOfNewline == -1) { int bytesPresent = bytesAvailableInBuffer(); if (bytesPresent > MAX_LINE_LENGTH) { throw new RuntimeException( "Really, you have a line longer than " + MAX_LINE_LENGTH + " bytes?"); } // next time through, start where we left off. startFrom = bytesPresent; int bytesRead = fillBuffer(8 * 1024); if (bytesRead == -1) { int bytesRemaining = bytesAvailableInBuffer(); return consumeBytesFromBuffer(bytesRemaining); } } else { int length = indexOfNewline - bufferReadHead + 1; return consumeBytesFromBuffer(length); } } while (true); } private byte[] readToEof() throws IOException { if (bufferReadHead > 0) { compactBuffer(true); } ByteStreams.copy(stream, buffer); int length = buffer.getLength(); if (length == 0) { return new byte[0]; } else { return consumeBytesFromBuffer(length); } } private byte[] readTo(int length) throws IOException { if (length == 0) { return new byte[0]; } if (bufferReadHead > 0) { compactBuffer(true); } int bytesStillNeeded = length - buffer.getLength(); if (bytesStillNeeded > 0) { int bytesRead = fillBuffer(bytesStillNeeded); while (bytesRead != -1 && bytesStillNeeded > 0) { bytesStillNeeded -= bytesRead; bytesRead = fillBuffer(bytesStillNeeded); } } return consumeBytesFromBuffer(length); } private int bytesAvailableInBuffer() { return buffer.getLength() - bufferReadHead; } private int indexOfNextNewlineInBuffer(int startFrom) { byte[] bytes = buffer.getBuffer(); int bufferLength = buffer.getLength(); for (int i = bufferReadHead + startFrom; i < bufferLength; i++) { if (bytes[i] == LINEFEED) { return i; } } return -1; } private int fillBuffer(int length) throws IOException { compactBuffer(false); byte[] readBuf = new byte[length]; int bytesRead = stream.read(readBuf); if (bytesRead > 0) { buffer.write(readBuf, 0, bytesRead); } return bytesRead; } private byte[] consumeBytesFromBuffer(int length) { int bytesAvailable = bytesAvailableInBuffer(); if (length > bytesAvailable) { length = bytesAvailable; } if (length == 0) { return null; } byte[] bytes = new byte[length]; byte[] bufferBytes = buffer.getBuffer(); System.arraycopy(bufferBytes, bufferReadHead, bytes, 0, length); bufferReadHead += length; return bytes; } private void compactBuffer(boolean force) { byte[] bufferBytes = buffer.getBuffer(); // normally, only compact if we're at least 1K in, and at least 3/4 of the way in if (force || (bufferReadHead > 1024 && bufferReadHead > (bufferBytes.length * 3 / 4))) { int remainingBytes = bytesAvailableInBuffer(); System.arraycopy(bufferBytes, bufferReadHead, bufferBytes, 0, remainingBytes); buffer.setLength(remainingBytes); bufferReadHead = 0; } } }
5,597
0
Create_ds/rack-servlet/core/src/main/java/com/squareup
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/package-info.java
/* * Copyright (C) 2013 Square, 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. */ /** * The {@link com.squareup.rack.RackApplication} interface and its collaborators. */ package com.squareup.rack;
5,598
0
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack
Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/servlet/RackServlet.java
/* * Copyright (C) 2013 Square, 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.squareup.rack.servlet; import com.squareup.rack.RackApplication; import com.squareup.rack.RackEnvironment; import com.squareup.rack.RackResponse; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p>Hosts a {@link RackApplication}.</p> * * <p>Since RackServlet lacks a zero-argument constructor, you'll need to manually instantiate and * install it in your container, rather than declaring it in a {@code web.xml} file. See our * examples for concrete code.</p> */ public class RackServlet extends HttpServlet { private final RackEnvironmentBuilder rackEnvironmentBuilder; private final RackApplication rackApplication; private final RackResponsePropagator rackResponsePropagator; /** * Creates a servlet hosting the given {@link RackApplication}. * * @param rackApplication the application to host. */ public RackServlet(RackApplication rackApplication) { this(new RackEnvironmentBuilder(), rackApplication, new RackResponsePropagator()); } /** * Creates a servlet hosting the given {@link RackApplication} and that uses the given * collaborators to translate between the Servlet and Rack environments. * * @param rackEnvironmentBuilder turns {@link HttpServletRequest}s into {@link RackEnvironment}s. * @param rackApplication the application to host. * @param rackResponsePropagator writes {@link RackResponse}s onto {@link HttpServletResponse}s. */ public RackServlet(RackEnvironmentBuilder rackEnvironmentBuilder, RackApplication rackApplication, RackResponsePropagator rackResponsePropagator) { this.rackEnvironmentBuilder = rackEnvironmentBuilder; this.rackApplication = rackApplication; this.rackResponsePropagator = rackResponsePropagator; } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RackEnvironment rackEnvironment = rackEnvironmentBuilder.build(request); try { RackResponse rackResponse = rackApplication.call(rackEnvironment); rackResponsePropagator.propagate(rackResponse, response); } finally { rackEnvironment.closeRackInput(); } } }
5,599