Compare commits

...

10 Commits

Author SHA1 Message Date
Zhiwei Xue
cebfe678b1 feat(TUP-23774):Update studio with update-site mechanism. 2019-09-16 15:28:02 +08:00
Zhiwei Xue
5bdc4ceef7 fix(TUP-24310):routines is duplicated in the reactor (#2706) 2019-09-12 10:33:49 +08:00
SunChaoqun
d2eaeb7b97 TESB-26415:Cannot publish Route with Routelet to snapshots when project (#2702)
has a ref project defined
2019-09-11 17:14:03 +08:00
hzhao-talendbj
a53ffdfbf4 feat(TUP-24028)Add Azure datacenter part of the studio connection (#2685) 2019-09-11 17:11:57 +08:00
hzhao-talendbj
dc92855b54 fix(TUP-23555)Unnecessary xmlMappings will be included in a built job (#2699) 2019-09-09 10:52:49 +08:00
Chao MENG
e8d1ce17d0 fix(TUP-23905): Job disappearing after merging git branches (#2703)
fix(TUP-23905): Job disappearing after merging git branches
https://jira.talendforge.org/browse/TUP-23905
2019-09-09 10:44:37 +08:00
Chao MENG
ba19f14fc9 fix(TUP-23905): Job disappearing after merging git branches (#2700)
fix(TUP-23905): Job disappearing after merging git branches
https://jira.talendforge.org/browse/TUP-23905
2019-09-06 10:12:06 +08:00
Zhiwei Xue
1a73160d6b fix(TUP-24323):_tdm folder is missing after build thmap job (#2687) 2019-09-03 10:17:48 +08:00
jiezhang-tlnd
6efbc76223 fix(TUP-24411)Error message: unable to update task config if the Context parameters have same values but different case (#2691)
* fix(TUP-24411)Error message: unable to update task config if the Context
parameters have same values but different case
https://jira.talendforge.org/browse/TUP-24411

* fix(TUP-24411)Error message: unable to update task config if the Context
parameters have same values but different case.
https://jira.talendforge.org/browse/TUP-24411

* fix(TUP-24411)Error message: unable to update task config if the Context
parameters have same values but different case

* fix(TUP-24411)Error message: unable to update task config if the Context
parameters have same values but different case
https://jira.talendforge.org/browse/TUP-24411

* fix(TUP-24411)Error message: unable to update task config if the Context
parameters have same values but different case
https://jira.talendforge.org/browse/TUP-24411

* fix(TUP-24411)Error message: unable to update task config if the Context
parameters have same values but different case
https://jira.talendforge.org/browse/TUP-24411
2019-09-02 11:28:05 +08:00
Richard Lecomte
2aae24829a fix : TDI-42776 (#2692)
* fix : TDI-42776

Numeric sequence is now thread safe
2019-08-30 10:50:32 +02:00
32 changed files with 973 additions and 247 deletions

View File

@@ -98,6 +98,15 @@ public class JobContext implements IContext, Cloneable {
return true;
}
public boolean containsSameParameterIgnoreCase(String parameterName) {
for (IContextParameter contextParam : contextParameterList) {
if (contextParam.getName() != null && contextParam.getName().equalsIgnoreCase(parameterName)) {
return true;
}
}
return false;
}
/**
* Commented by Marvin Wang on Mar.2, 2012, the user who invokes the method should notice that if the
* <code>JobContext</code> has more than one <code>ContextParameter</code>s which names are same, this case will

View File

@@ -62,4 +62,6 @@ public interface IContext {
public IContext clone();
public boolean sameAs(IContext context);
public boolean containsSameParameterIgnoreCase(String parameterName);
}

View File

@@ -917,9 +917,12 @@ public final class ProcessUtils {
for (ProjectReference ref : references) {
all.addAll(factory.getAll(new Project(ref.getReferencedProject()), beansType));
}
if (!all.isEmpty()) { // has bean
return true;
}
// if (!all.isEmpty()) { // has bean
// return true;
// }
return true;
} catch (PersistenceException e) {
ExceptionHandler.process(e);
}

View File

@@ -42,6 +42,8 @@ public interface MavenConstants {
static final String POM_FILTER = "POM_FILTER";
static final String USE_PROFILE_MODULE = "USE_PROFILE_MODULE";
/*
* for lib
*/

View File

@@ -12,10 +12,13 @@
// ============================================================================
package org.talend.core.service;
import org.eclipse.core.runtime.IProgressMonitor;
import org.talend.core.IService;
public interface IUpdateService extends IService {
boolean checkComponentNexusUpdate();
boolean checkStudioUpdate(IProgressMonitor monitor);
}

View File

@@ -19,6 +19,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
@@ -97,17 +98,24 @@ public abstract class AbstractRoutineSynchronizer implements ITalendSynchronizer
private void getReferencedProjectRoutine(final Map<String, RoutineItem> beansList, final Project project,
ERepositoryObjectType routineType, boolean syncRef) throws SystemException {
for (IRepositoryViewObject obj : getRepositoryService().getProxyRepositoryFactory().getAll(project, routineType)) {
final String key = obj.getProperty().getLabel();
// it does not have a routine with same name
if (!beansList.containsKey(key)) {
beansList.put(key, (RoutineItem) obj.getProperty().getItem());
}
if (syncRef) {
// sync routine
syncRoutine((RoutineItem) obj.getProperty().getItem(), false, true, true);
List<IRepositoryViewObject> list = getRepositoryService().getProxyRepositoryFactory().getAll(project, routineType);
if (list.size() == 0) {
getRunProcessService().getTalendCodeJavaProject(routineType, project.getTechnicalLabel());
} else {
for (IRepositoryViewObject obj : list) {
final String key = obj.getProperty().getLabel();
// it does not have a routine with same name
if (!beansList.containsKey(key)) {
beansList.put(key, (RoutineItem) obj.getProperty().getItem());
}
if (syncRef) {
// sync routine
syncRoutine((RoutineItem) obj.getProperty().getItem(), false, true, true);
}
}
}
if (syncRef) {
// sync system routine
syncSystemRoutine(project);

View File

@@ -195,4 +195,7 @@ public interface IDesignerCoreService extends IService {
public void setTACReadTimeout(int timeout);
boolean isDelegateNode(INode node);
boolean isNeedContextInJar(IProcess process);
}

View File

@@ -98,6 +98,8 @@ public class RepositoryConstants {
public static final String REPOSITORY_CLOUD_APAC_ID = "cloud_apac"; //$NON-NLS-1$
public static final String REPOSITORY_CLOUD_US_WEST_ID = "cloud_us_west"; //$NON-NLS-1$
public static final String REPOSITORY_CLOUD_CUSTOM_ID = "cloud_custom"; //$NON-NLS-1$
public static final String REPOSITORY_URL = "url"; //$NON-NLS-1$

View File

@@ -472,7 +472,7 @@ public class ContextNebulaGridComposite extends AbstractContextTabEditComposite
paramNameFound = true;
paramName = NEW_PARAM_NAME + numParam;
for (int i = 0; i < listParams.size(); i++) {
if (paramName.equals(listParams.get(i).getName())) {
if (paramName.equalsIgnoreCase(listParams.get(i).getName())) {
paramNameFound = false;
}
}

View File

@@ -715,6 +715,13 @@ public class SelectRepositoryContextDialog extends SelectionDialog {
if (param != null && param.isBuiltIn()) {
return false;
}
if (param == null) {
boolean containsSameParameterIgnoreCase = manager.getDefaultContext()
.containsSameParameterIgnoreCase(paramType.getName());
if (containsSameParameterIgnoreCase) {
return false;
}
}
}
return true;
}

View File

@@ -756,7 +756,7 @@ public class ProcessorUtilities {
public static boolean hasMetadataDynamic(IProcess currentProcess, JobInfo jobInfo) {
boolean hasDynamicMetadata = false;
if (GlobalServiceRegister.getDefault().isServiceRegistered(IDesignerCoreService.class)) {
if (GlobalServiceRegister.getDefault().isServiceRegistered(IDesignerCoreService.class) && !isExportConfig()) {
IDesignerCoreService designerCoreService =
(IDesignerCoreService) GlobalServiceRegister.getDefault().getService(IDesignerCoreService.class);
for (INode node : currentProcess.getGraphicalNodes()) {
@@ -1231,14 +1231,24 @@ public class ProcessorUtilities {
public static void cleanSourceFolder(IProgressMonitor progressMonitor, IProcess currentProcess,
IProcessor processor) {
try {
ITalendProcessJavaProject jobProject = processor.getTalendJavaProject();
// clean up source code
IPath codePath = processor.getSrcCodePath().removeLastSegments(2);
IFolder srcFolder = processor.getTalendJavaProject().getProject().getFolder(codePath);
IFolder srcFolder = jobProject.getProject().getFolder(codePath);
String jobPackageFolder = JavaResourcesHelper.getJobClassPackageFolder(currentProcess);
for (IResource resource : srcFolder.members()) {
if (!resource.getProjectRelativePath().toPortableString().endsWith(jobPackageFolder)) {
resource.delete(true, progressMonitor);
}
}
// clean up resources folder if needed
if (ProcessorUtilities.isExportConfig() && !designerCoreService.isNeedContextInJar(currentProcess)) {
for (IResource resource : jobProject.getResourcesFolder().members()) {
if (resource.exists()) {
resource.delete(true, progressMonitor);
}
}
}
} catch (CoreException e) {
ExceptionHandler.process(e);
}

View File

@@ -11,4 +11,5 @@ ProjectPomProjectSettingPage_FilterPomLabel=Filter to use to generate poms:
ProjectPomProjectSettingPage_FilterErrorMessage=Invalid filter: {0}
ProjectPomProjectSettingPage.syncAllPomsButtonText=Force full re-synchronize poms
AbstractPersistentProjectSettingPage.syncAllPoms=Do you want to update all poms? \n This operation might take long time depends on your project size.
MavenProjectSettingPage.filterExampleMessage=Filter examples:\nlabel=myJob \t\t\t\t=> Generate only the job named "myJob"\n!(label=myJob) \t\t\t\t=> Generate any job except the one named "myJob"\n(path=folder1/folder2) \t\t\t=> Generate any job in the folder "folder1/folder2"\n(path=folder1/folder2)or(label=myJob)\t=> Generate any job in the folder "folder1/folder2" or named "myJob"\n(label=myJob)and(version=0.2) \t=> Generate only the job named "myJob" with version 0.2\n!((label=myJob)and(version=0.1)) \t=> Generate every jobs except the "myJob" version 0.1
MavenProjectSettingPage.filterExampleMessage=Filter examples:\nlabel=myJob \t\t\t\t=> Generate only the job named "myJob"\n!(label=myJob) \t\t\t\t=> Generate any job except the one named "myJob"\n(path=folder1/folder2) \t\t\t=> Generate any job in the folder "folder1/folder2"\n(path=folder1/folder2)or(label=myJob)\t=> Generate any job in the folder "folder1/folder2" or named "myJob"\n(label=myJob)and(version=0.2) \t=> Generate only the job named "myJob" with version 0.2\n!((label=myJob)and(version=0.1)) \t=> Generate every jobs except the "myJob" version 0.1
MavenProjectSettingPage.refModuleText=Set reference project modules in profile

View File

@@ -198,6 +198,7 @@ public class M2eUserSettingForTalendLoginTask extends AbstractLoginTask {
// add one marker to check to sync or not.
File repoFolder = new File(maven.getLocalRepositoryPath());
File markerFile = new File(repoFolder, ".syncMarker"); //$NON-NLS-1$
System.setProperty("m2.syncmarker.path", markerFile.getAbsolutePath()); //$NON-NLS-1$
Properties prop = new Properties();
FileInputStream inStream = null;
FileOutputStream outputStream = null;

View File

@@ -50,6 +50,8 @@ public class MavenProjectSettingPage extends AbstractProjectSettingPage {
private IPreferenceStore preferenceStore;
private Button useProfileModuleCheckbox;
public MavenProjectSettingPage() {
noDefaultAndApplyButton();
}
@@ -84,6 +86,10 @@ public class MavenProjectSettingPage extends AbstractProjectSettingPage {
filterExampleLable.setText(Messages.getString("MavenProjectSettingPage.filterExampleMessage")); //$NON-NLS-1$
filterExampleLable.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
useProfileModuleCheckbox = new Button(parent, SWT.CHECK);
useProfileModuleCheckbox.setText(Messages.getString("MavenProjectSettingPage.refModuleText")); //$NON-NLS-1$
useProfileModuleCheckbox.setSelection(preferenceStore.getBoolean(MavenConstants.USE_PROFILE_MODULE));
filterText.setText(filter);
filterText.addModifyListener(new ModifyListener() {
@@ -115,6 +121,7 @@ public class MavenProjectSettingPage extends AbstractProjectSettingPage {
public void widgetSelected(SelectionEvent event) {
try {
preferenceStore.setValue(MavenConstants.POM_FILTER, getRealVersionFilter(filter));
preferenceStore.setValue(MavenConstants.USE_PROFILE_MODULE, useProfileModuleCheckbox.getSelection());
new AggregatorPomsHelper().syncAllPoms();
} catch (Exception e) {
ExceptionHandler.process(e);
@@ -133,6 +140,7 @@ public class MavenProjectSettingPage extends AbstractProjectSettingPage {
boolean ok = super.performOk();
if (preferenceStore != null) {
preferenceStore.setValue(MavenConstants.POM_FILTER, getRealVersionFilter(filter));
preferenceStore.setValue(MavenConstants.USE_PROFILE_MODULE, useProfileModuleCheckbox.getSelection());
}
return ok;
}

View File

@@ -12,24 +12,22 @@
// ============================================================================
package org.talend.designer.maven.tools;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_AGGREGATORS;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_BEANS;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_CODES;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_JOBS;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_PIGUDFS;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_POMS;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.DIR_ROUTINES;
import static org.talend.designer.maven.model.TalendJavaProjectConstants.*;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Activation;
import org.apache.maven.model.Model;
import org.apache.maven.model.Profile;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
@@ -56,7 +54,6 @@ import org.talend.core.context.Context;
import org.talend.core.context.RepositoryContext;
import org.talend.core.model.general.ILibrariesService;
import org.talend.core.model.general.ModuleNeeded;
import org.talend.core.model.general.Project;
import org.talend.core.model.process.ProcessUtils;
import org.talend.core.model.properties.Item;
import org.talend.core.model.properties.ProjectReference;
@@ -110,27 +107,29 @@ public class AggregatorPomsHelper {
return projectTechName;
}
public void createRootPom(List<String> modules, boolean force, IProgressMonitor monitor) throws Exception {
public void createRootPom(Model model, boolean force, IProgressMonitor monitor)
throws Exception {
IFile pomFile = getProjectRootPom();
if (force || !pomFile.exists()) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(MavenTemplateManager.KEY_PROJECT_NAME, projectTechName);
Model model = MavenTemplateManager.getCodeProjectTemplateModel(parameters);
if (modules != null && !modules.isEmpty()) {
model.setModules(modules);
if (model == null) {
model = getCodeProjectTemplateModel();
}
PomUtil.savePom(monitor, model, pomFile);
}
}
public void createRootPom(IProgressMonitor monitor) throws Exception {
Model newModel = getCodeProjectTemplateModel();
IFile pomFile = getProjectRootPom();
List<String> modules = null;
if (pomFile != null && pomFile.exists()) {
Model model = MavenPlugin.getMavenModelManager().readMavenModel(pomFile);
modules = model.getModules();
Model oldModel = MavenPlugin.getMavenModelManager().readMavenModel(pomFile);
List<Profile> profiles = oldModel.getProfiles().stream()
.filter(profile -> StringUtils.startsWithIgnoreCase(profile.getId(), projectTechName))
.collect(Collectors.toList());
newModel.setModules(oldModel.getModules());
newModel.getProfiles().addAll(profiles);
}
createRootPom(modules, true, monitor);
createRootPom(newModel, true, monitor);
}
public void installRootPom(boolean force) throws Exception {
@@ -290,37 +289,38 @@ public class AggregatorPomsHelper {
}
}
public void updateRefProjectModules(List<ProjectReference> references) {
public void updateRefProjectModules(List<ProjectReference> references, IProgressMonitor monitor) {
if (!needUpdateRefProjectModules()) {
return;
}
try {
List<String> modules = new ArrayList<>();
for (ProjectReference reference : references) {
String refProjectTechName = reference.getReferencedProject().getTechnicalLabel();
String modulePath = "../../" + refProjectTechName + "/" + TalendJavaProjectConstants.DIR_POMS; //$NON-NLS-1$ //$NON-NLS-2$
modules.add(modulePath);
Model model = MavenPlugin.getMavenModelManager().readMavenModel(getProjectRootPom());
if (PomIdsHelper.useProfileModule()) {
List<Profile> profiles = collectRefProjectProfiles(references);
Iterator<Profile> iterator = model.getProfiles().listIterator();
iterator.forEachRemaining(profile -> {
if (StringUtils.startsWithIgnoreCase(profile.getId(), projectTechName)) {
iterator.remove();
}
});
model.getProfiles().addAll(profiles);
} else {
List<String> refPrjectModules = new ArrayList<>();
references.forEach(reference -> {
String refProjectTechName = reference.getReferencedProject().getTechnicalLabel();
String modulePath = "../../" + refProjectTechName + "/" + TalendJavaProjectConstants.DIR_POMS; //$NON-NLS-1$ //$NON-NLS-2$
refPrjectModules.add(modulePath);
});
List<String> modules = model.getModules();
Iterator<String> iterator = modules.listIterator();
iterator.forEachRemaining(modulePath -> {
if (modulePath.startsWith("../../")) { //$NON-NLS-1$
iterator.remove();
}
});
modules.addAll(refPrjectModules);
}
Project mainProject = ProjectManager.getInstance().getCurrentProject();
IFolder mainPomsFolder = new AggregatorPomsHelper(mainProject.getTechnicalLabel()).getProjectPomsFolder();
IFile mainPomFile = mainPomsFolder.getFile(TalendMavenConstants.POM_FILE_NAME);
Model model = MavenPlugin.getMavenModelManager().readMavenModel(mainPomFile);
List<String> oldModules = model.getModules();
if (oldModules == null) {
oldModules = new ArrayList<>();
}
ListIterator<String> iterator = oldModules.listIterator();
while (iterator.hasNext()) {
String modulePath = iterator.next();
if (modulePath.startsWith("../../")) { //$NON-NLS-1$
iterator.remove();
}
}
oldModules.addAll(modules);
PomUtil.savePom(null, model, mainPomFile);
createRootPom(model, true, monitor);
} catch (Exception e) {
ExceptionHandler.process(e);
}
@@ -710,47 +710,48 @@ public class AggregatorPomsHelper {
return null;
}
private void collectModules(List<String> modules) {
IRunProcessService service = getRunProcessService();
if (service != null) {
modules.add(
getModulePath(service.getTalendCodeJavaProject(ERepositoryObjectType.ROUTINES).getProjectPom()));
if (ProcessUtils.isRequiredPigUDFs(null)) {
modules.add(
getModulePath(service.getTalendCodeJavaProject(ERepositoryObjectType.PIG_UDF).getProjectPom()));
}
if (ProcessUtils.isRequiredBeans(null)) {
modules.add(getModulePath(service
.getTalendCodeJavaProject(ERepositoryObjectType.valueOf("BEANS")) //$NON-NLS-1$
.getProjectPom()));
}
private List<Profile> collectRefProjectProfiles(List<ProjectReference> references) throws CoreException {
if (!needUpdateRefProjectModules()) {
Model model = MavenPlugin.getMavenModelManager().readMavenModel(getProjectRootPom());
List<Profile> profiles = model.getProfiles();
return profiles.stream().filter(profile -> StringUtils.startsWithIgnoreCase(profile.getId(), projectTechName))
.collect(Collectors.toList());
}
if (needUpdateRefProjectModules()) {
List<ProjectReference> references =
ProjectManager.getInstance().getCurrentProject().getProjectReferenceList(true);
for (ProjectReference reference : references) {
String refProjectTechName = reference.getReferencedProject().getTechnicalLabel();
String modulePath = "../../" + refProjectTechName + "/" + TalendJavaProjectConstants.DIR_POMS; //$NON-NLS-1$ //$NON-NLS-2$
modules.add(modulePath);
}
} else {
Project mainProject = ProjectManager.getInstance().getCurrentProject();
IFolder mainPomsFolder = new AggregatorPomsHelper(mainProject.getTechnicalLabel()).getProjectPomsFolder();
IFile mainPomFile = mainPomsFolder.getFile(TalendMavenConstants.POM_FILE_NAME);
try {
Model model = MavenPlugin.getMavenModelManager().readMavenModel(mainPomFile);
List<String> oldModules = model.getModules();
if (oldModules != null) {
for (String modulePath : oldModules) {
if (modulePath.startsWith("../../")) { //$NON-NLS-1$
modules.add(modulePath);
}
}
}
} catch (CoreException e) {
ExceptionHandler.process(e);
}
if (references == null) {
references = ProjectManager.getInstance().getCurrentProject().getProjectReferenceList(true);
}
List<Profile> profiles = new ArrayList<>();
references.forEach(reference -> {
String refProjectTechName = reference.getReferencedProject().getTechnicalLabel();
String modulePath = "../../" + refProjectTechName + "/" + TalendJavaProjectConstants.DIR_POMS; //$NON-NLS-1$ //$NON-NLS-2$
Profile profile = new Profile();
profile.setId((projectTechName + "_" + refProjectTechName).toLowerCase()); //$NON-NLS-1$
Activation activation = new Activation();
activation.setActiveByDefault(true);
profile.setActivation(activation);
profile.getModules().add(modulePath);
profiles.add(profile);
});
return profiles;
}
private List<String> collectRefProjectModules(List<ProjectReference> references) throws CoreException {
if (!needUpdateRefProjectModules()) {
Model model = MavenPlugin.getMavenModelManager().readMavenModel(getProjectRootPom());
return model.getModules().stream().filter(modulePath -> modulePath.startsWith("../../")) //$NON-NLS-1$
.collect(Collectors.toList());
}
if (references == null) {
references = ProjectManager.getInstance().getCurrentProject().getProjectReferenceList(true);
}
List<String> modules = new ArrayList<>();
references.forEach(reference -> {
String refProjectTechName = reference.getReferencedProject().getTechnicalLabel();
String modulePath = "../../" + refProjectTechName + "/" + TalendJavaProjectConstants.DIR_POMS; //$NON-NLS-1$ //$NON-NLS-2$
modules.add(modulePath);
});
return modules;
}
public boolean needUpdateRefProjectModules() {
@@ -841,8 +842,15 @@ public class AggregatorPomsHelper {
}
// sync project pom again with all modules.
monitor.subTask("Synchronize project pom with modules"); //$NON-NLS-1$
collectModules(modules);
createRootPom(modules, true, monitor);
collectCodeModules(modules);
Model model = getCodeProjectTemplateModel();
if (PomIdsHelper.useProfileModule()) {
model.getProfiles().addAll(collectRefProjectProfiles(null));
} else {
modules.addAll(collectRefProjectModules(null));
}
model.setModules(modules);
createRootPom(model, true, monitor);
installRootPom(true);
monitor.worked(1);
if (monitor.isCanceled()) {
@@ -851,6 +859,21 @@ public class AggregatorPomsHelper {
monitor.done();
}
private void collectCodeModules(List<String> modules) {
// collect codes modules
IRunProcessService service = getRunProcessService();
if (service != null) {
modules.add(getModulePath(service.getTalendCodeJavaProject(ERepositoryObjectType.ROUTINES).getProjectPom()));
if (ProcessUtils.isRequiredPigUDFs(null)) {
modules.add(getModulePath(service.getTalendCodeJavaProject(ERepositoryObjectType.PIG_UDF).getProjectPom()));
}
if (ProcessUtils.isRequiredBeans(null)) {
modules.add(getModulePath(service.getTalendCodeJavaProject(ERepositoryObjectType.valueOf("BEANS")) //$NON-NLS-1$
.getProjectPom()));
}
}
}
/**
* Check if is a esb data service job
*
@@ -879,6 +902,12 @@ public class AggregatorPomsHelper {
return null;
}
private Model getCodeProjectTemplateModel() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(MavenTemplateManager.KEY_PROJECT_NAME, projectTechName);
return MavenTemplateManager.getCodeProjectTemplateModel(parameters);
}
private static IRunProcessService getRunProcessService() {
if (GlobalServiceRegister.getDefault().isServiceRegistered(IRunProcessService.class)) {
IRunProcessService runProcessService =

View File

@@ -260,6 +260,12 @@ public class PomIdsHelper {
return manager.getValue(MavenConstants.POM_FILTER);
}
public static boolean useProfileModule() {
String projectTechName = ProjectManager.getInstance().getCurrentProject().getTechnicalLabel();
ProjectPreferenceManager manager = getPreferenceManager(projectTechName);
return manager.getBoolean(MavenConstants.USE_PROFILE_MODULE);
}
private static String getGroupId(String projectTechName, String baseName, Property property) {
if (projectTechName == null) {
projectTechName = ProjectManager.getInstance().getCurrentProject().getTechnicalLabel();

View File

@@ -6,10 +6,11 @@
package routines;
import java.math.BigDecimal;
import java.util.concurrent.ConcurrentHashMap;
public class Numeric {
private static final java.util.Map<String, Integer> seq_Hash = new java.util.HashMap<String, Integer>();
private static final java.util.Map<String, Integer> seq_Hash = new ConcurrentHashMap<>();
/**
* return an incremented numeric id
@@ -30,13 +31,8 @@ public class Numeric {
*
*/
public static Integer sequence(String seqName, int startValue, int step) {
if (seq_Hash.containsKey(seqName)) {
seq_Hash.put(seqName, seq_Hash.get(seqName) + step);
return seq_Hash.get(seqName);
} else {
seq_Hash.put(seqName, startValue);
return startValue;
}
return seq_Hash.compute(seqName,
(String k, Integer v) -> v == null ? startValue : v + step);
}
/**
@@ -68,9 +64,7 @@ public class Numeric {
*/
public static void removeSequence(String seqName) {
if (seq_Hash.containsKey(seqName)) {
seq_Hash.remove(seqName);
}
seq_Hash.remove(seqName);
}
/**

View File

@@ -1672,7 +1672,7 @@ public final class ConnectionContextHelper {
}
}
for (String var : neededVars) {
if (context.getContextParameter(var) != null) {
if (context.containsSameParameterIgnoreCase(var)) {
continue;
}
ContextParameterType param = ContextUtils.getContextParameterTypeByName(type, var);

View File

@@ -55,6 +55,7 @@ import org.talend.core.model.migration.IMigrationToolService;
import org.talend.core.model.utils.TalendPropertiesUtil;
import org.talend.core.repository.CoreRepositoryPlugin;
import org.talend.core.runtime.services.IMavenUIService;
import org.talend.core.service.IUpdateService;
import org.talend.core.services.ICoreTisService;
import org.talend.core.ui.branding.IBrandingService;
import org.talend.core.ui.workspace.ChooseWorkspaceData;
@@ -156,8 +157,15 @@ public class Application implements IApplication {
(IMigrationToolService) GlobalServiceRegister.getDefault().getService(IMigrationToolService.class);
service.executeWorspaceTasks();
// saveConnectionBean(email);
boolean needRelaunch = false;
if (GlobalServiceRegister.getDefault().isServiceRegistered(IUpdateService.class)) {
IUpdateService updateService = GlobalServiceRegister.getDefault().getService(IUpdateService.class);
needRelaunch = updateService.checkStudioUpdate(new NullProgressMonitor());
}
if (needRelaunch) {
setRelaunchData();
return IApplication.EXIT_RELAUNCH;
}
final PatchComponent patchComponent = PatchComponentHelper.getPatchComponent();
if (patchComponent != null) {
final boolean installed = patchComponent.install();

View File

@@ -24,6 +24,9 @@ ImportItemsWizardPage_sameIdProblemMessage=The 2 following items haves the same
ImportItemsWizardPage_TarImport_badFormat = Source file is not a valid tar file.
ImportItemsWizardPage_ZipImport_badFormat = Source file is not a valid Zip file.
ImportItemsWizardPage_ErrorsMessage=The item '{0}' with different version {1} exists. Check the Recycle bin and empty it if needed.
ImportItemsWizardPage_internalIdGroup=Internal id
ImportItemsWizardPage_internalIdGroup_alwaysRegenId=Always regenerate id when import
ImportItemsWizardPage_internalIdGroup_keepOrigId=Keep original internal id
ImportItemsAction_title=Import items

View File

@@ -50,6 +50,9 @@ import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
@@ -57,6 +60,7 @@ import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
@@ -141,6 +145,8 @@ public class ImportItemsWizardPage extends WizardPage {
private final ImportExportHandlersManager importManager = new ImportExportHandlersManager();
private Button regenIdBtn;
/**
*
* DOC ggu ImportItemsWizardPage constructor comment.
@@ -498,8 +504,29 @@ public class ImportItemsWizardPage extends WizardPage {
* @param workArea
*/
private void createAdditionArea(Composite workArea) {
Composite optionsArea = new Composite(workArea, SWT.NONE);
FormLayout optAreaLayout = new FormLayout();
optionsArea.setLayout(optAreaLayout);
GridData gridData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH);
optionsArea.setLayoutData(gridData);
Group internalIdGroup = new Group(optionsArea, SWT.NONE);
internalIdGroup.setText(Messages.getString("ImportItemsWizardPage_internalIdGroup"));
internalIdGroup.setLayout(new GridLayout(1, true));
FormData internalIdGroupLayoutData = new FormData();
internalIdGroupLayoutData.top = new FormAttachment(0);
internalIdGroupLayoutData.left = new FormAttachment(0);
internalIdGroup.setLayoutData(internalIdGroupLayoutData);
regenIdBtn = new Button(internalIdGroup, SWT.RADIO);
regenIdBtn.setText(Messages.getString("ImportItemsWizardPage_internalIdGroup_alwaysRegenId"));
regenIdBtn.setSelection(true);
Button keepOrigIdBtn = new Button(internalIdGroup, SWT.RADIO);
keepOrigIdBtn.setText(Messages.getString("ImportItemsWizardPage_internalIdGroup_keepOrigId"));
// see feature 3949
this.overwriteButton = new Button(workArea, SWT.CHECK);
this.overwriteButton = new Button(optionsArea, SWT.CHECK);
this.overwriteButton.setText(Messages.getString("ImportItemsWizardPage_overwriteItemsText")); //$NON-NLS-1$
this.overwriteButton.addSelectionListener(new SelectionAdapter() {
@@ -511,6 +538,11 @@ public class ImportItemsWizardPage extends WizardPage {
}
});
FormData overwriteLayoutData = new FormData();
overwriteLayoutData.top = new FormAttachment(internalIdGroup, 5, SWT.BOTTOM);
overwriteLayoutData.left = new FormAttachment(internalIdGroup, 0, SWT.LEFT);
this.overwriteButton.setLayoutData(overwriteLayoutData);
}
protected boolean isEnableForExchange() {
@@ -982,6 +1014,7 @@ public class ImportItemsWizardPage extends WizardPage {
}
final boolean overwrite = overwriteButton.getSelection();
final boolean alwaysRegenId = regenIdBtn.getSelection();
try {
IRunnableWithProgress iRunnableWithProgress = new IRunnableWithProgress() {
@@ -1008,7 +1041,7 @@ public class ImportItemsWizardPage extends WizardPage {
EmfResourcesFactoryReader.INSTANCE.addOption(importOption, false);
importManager.importItemRecords(monitor, resManager, checkedItemRecords, overwrite,
nodesBuilder.getAllImportItemRecords(), destinationPath);
nodesBuilder.getAllImportItemRecords(), destinationPath, alwaysRegenId);
} finally {
EmfResourcesFactoryReader.INSTANCE.removOption(importOption, false);
}

View File

@@ -417,6 +417,16 @@ public class ImportExportHandlersManager {
public void importItemRecords(final IProgressMonitor progressMonitor, final ResourcesManager resManager,
final List<ImportItem> checkedItemRecords, final boolean overwrite, final ImportItem[] allImportItemRecords,
final IPath destinationPath) throws InvocationTargetException {
importItemRecords(progressMonitor, resManager, checkedItemRecords, overwrite, allImportItemRecords, destinationPath,
/*
* disable by default, but provide possibility to enable it
*/
Boolean.getBoolean("studio.import.option.alwaysRegenId"));
}
public void importItemRecords(final IProgressMonitor progressMonitor, final ResourcesManager resManager,
final List<ImportItem> checkedItemRecords, final boolean overwrite, final ImportItem[] allImportItemRecords,
final IPath destinationPath, final boolean alwaysRegenId) throws InvocationTargetException {
TimeMeasure.display = CommonsPlugin.isDebugMode();
TimeMeasure.displaySteps = CommonsPlugin.isDebugMode();
TimeMeasure.measureActive = CommonsPlugin.isDebugMode();
@@ -536,15 +546,31 @@ public class ImportExportHandlersManager {
return;
}
if (itemRecord.isValid()) {
if (itemRecord.getState() == State.ID_EXISTED
|| itemRecord.getState() == State.NAME_AND_ID_EXISTED_BOTH) {
if (alwaysRegenId || itemRecord.getState() == State.ID_EXISTED
|| itemRecord.getState() == State.NAME_AND_ID_EXISTED_BOTH
|| itemRecord.getState() == State.NAME_EXISTED) {
String id = nameToIdMap.get(itemRecord.getProperty().getLabel()
+ ERepositoryObjectType.getItemType(itemRecord.getProperty().getItem())
.toString());
if (id == null) {
try {
if (overwrite && itemRecord.getState() == State.NAME_AND_ID_EXISTED_BOTH) {
boolean reuseExistingId = false;
if (overwrite && (itemRecord.getState() == State.NAME_AND_ID_EXISTED_BOTH
|| itemRecord.getState() == State.NAME_EXISTED)) {
// just try to reuse the id of the item which will be overwrited
reuseExistingId = true;
} else if (alwaysRegenId) {
switch (itemRecord.getState()) {
case NAME_EXISTED:
case NAME_AND_ID_EXISTED:
case NAME_AND_ID_EXISTED_BOTH:
reuseExistingId = true;
break;
default:
break;
}
}
if (reuseExistingId) {
IRepositoryViewObject object = itemRecord.getExistingItemWithSameName();
if (object != null) {
if (ProjectManager.getInstance().isInCurrentMainProject(

View File

@@ -24,6 +24,7 @@ import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Priority;
import org.eclipse.emf.common.util.EList;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.model.metadata.builder.connection.Connection;
@@ -123,68 +124,101 @@ public class ChangeIdManager {
public void changeIds() throws Exception {
buildRefIds2ItemIdsMap();
for (Map.Entry<String, String> entry : oldId2NewIdMap.entrySet()) {
changeId(entry.getValue(), entry.getKey());
}
}
private void changeId(String newId, String oldId) throws Exception {
Map<String, Set<String>> changeIdMap = buildChangeIdMap();
if (newId == null || StringUtils.equals(newId, oldId)) {
return;
}
Set<String> relationIds = new HashSet<String>();
Collection<String> itemIds = refIds2ItemIdsMap.get(oldId);
if (itemIds != null && !itemIds.isEmpty()) {
relationIds.addAll(itemIds);
}
List<Relation> relations = getRelations(oldId);
for (Relation relation : relations) {
String projectLabel = ProcessUtils.getProjectLabelFromItemId(relation.getId());
if (projectLabel != null
&& !projectLabel.equals(ProjectManager.getInstance().getCurrentProject().getTechnicalLabel())) {
continue;
}
relationIds.add(ProcessUtils.getPureItemId(relation.getId()));
}
if (relationIds.isEmpty()) {
return;
}
Set<String> changedIds = new HashSet<String>();
for (String relationId : relationIds) {
String id = relationId;
if (!oldId2NewIdMap.containsKey(id)) {
for (Map.Entry<String, Set<String>> entry : changeIdMap.entrySet()) {
String oldEffectedId = entry.getKey();
if (!oldId2NewIdMap.containsKey(oldEffectedId)) {
// means didn't import this item
continue;
}
if (changedIds.contains(id)) {
String newEffectedId = oldId2NewIdMap.get(oldEffectedId);
if (StringUtils.equals(oldEffectedId, newEffectedId)) {
continue;
} else {
changedIds.add(id);
}
List<ImportItem> importItems = id2ImportItemsMap.get(id);
ERepositoryObjectType repType = importItems.get(0).getRepositoryType();
String newRelatedId = oldId2NewIdMap.get(id);
if (newRelatedId == null) {
if (StringUtils.isBlank(newEffectedId)) {
// means the id didn't be changed
newRelatedId = id;
newEffectedId = oldEffectedId;
}
List<IRepositoryViewObject> repViewObjs = getAllVersion(newRelatedId, repType);
List<ImportItem> importItems = id2ImportItemsMap.get(oldEffectedId);
ERepositoryObjectType repType = importItems.get(0).getRepositoryType();
List<IRepositoryViewObject> repViewObjs = getAllVersion(newEffectedId, repType);
if (repViewObjs != null && !repViewObjs.isEmpty()) {
for (IRepositoryViewObject repViewObj : repViewObjs) {
Map<String, String> old2NewMap = new HashMap<>();
for (String oldId : entry.getValue()) {
String newId = oldId2NewIdMap.get(oldId);
if (StringUtils.equals(newId, oldId)) {
continue;
}
old2NewMap.put(oldId, newId);
}
Property property = repViewObj.getProperty();
changeRelated(newId, oldId, property, getCurrentProject());
changeRelated(old2NewMap, property, getCurrentProject());
String version = property.getVersion();
for (ImportItem importItem : importItems) {
if (StringUtils.equals(version, importItem.getItemVersion())) {
// update property, it will be used in following steps
importItem.setProperty(property);
break;
}
}
}
}
}
}
private Map<String, Set<String>> buildChangeIdMap() {
Map<String, Set<String>> effectedIdsMap = new HashMap<>();
for (Map.Entry<String, String> entry : oldId2NewIdMap.entrySet()) {
String oldId = entry.getKey();
String newId = entry.getValue();
if (newId == null || StringUtils.equals(newId, oldId)) {
continue;
}
Set<String> relationIds = new HashSet<String>();
Collection<String> itemIds = refIds2ItemIdsMap.get(oldId);
if (itemIds != null && !itemIds.isEmpty()) {
relationIds.addAll(itemIds);
}
List<Relation> relations = getRelations(oldId);
for (Relation relation : relations) {
relationIds.add(ProcessUtils.getPureItemId(relation.getId()));
}
if (relationIds.isEmpty()) {
continue;
}
Set<String> idSet = effectedIdsMap.get(oldId);
if (idSet == null) {
idSet = new HashSet<>();
effectedIdsMap.put(oldId, idSet);
}
idSet.addAll(relationIds);
}
Map<String, Set<String>> changeIdMap = new HashMap<>();
for (Map.Entry<String, Set<String>> entry : effectedIdsMap.entrySet()) {
String oldId = entry.getKey();
Set<String> effectedIds = entry.getValue();
for (String effectedId : effectedIds) {
Set<String> changeSet = changeIdMap.get(effectedId);
if (changeSet == null) {
changeSet = new HashSet<>();
changeIdMap.put(effectedId, changeSet);
}
changeSet.add(oldId);
}
}
return changeIdMap;
}
private List<IRepositoryViewObject> getAllVersion(String id, ERepositoryObjectType repType) throws Exception {
List<IRepositoryViewObject> repViewObjs = null;
if (repType != null) {
@@ -253,16 +287,16 @@ public class ChangeIdManager {
return relations;
}
private void changeRelated(String newId, String oldId, Property property, org.talend.core.model.general.Project project)
throws Exception {
private void changeRelated(Map<String, String> old2NewMap, Property property,
org.talend.core.model.general.Project project) throws Exception {
Item item = property.getItem();
boolean modified = false;
if (item instanceof ProcessItem) {
modified = changeRelatedProcess(newId, oldId, item);
modified = changeRelatedProcess(old2NewMap, item);
} else if (item instanceof JobletProcessItem) {
modified = changeRelatedProcess(newId, oldId, item);
modified = changeRelatedProcess(old2NewMap, item);
} else if (item instanceof ConnectionItem) {
modified = changeRelatedConnection(newId, oldId, (ConnectionItem) item);
modified = changeRelatedConnection(old2NewMap, (ConnectionItem) item);
} else {
throw new Exception("Unsupported id change: id[" + property.getId() + "], name[" + property.getLabel() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
@@ -272,22 +306,41 @@ public class ChangeIdManager {
}
}
private boolean changeRelatedConnection(String newId, String oldId, ConnectionItem item) throws Exception {
private boolean changeRelatedConnection(Map<String, String> old2NewMap, ConnectionItem item) throws Exception {
boolean modified = false;
Connection conn = item.getConnection();
String ctxId = conn.getContextId();
if (StringUtils.equals(oldId, ctxId)) {
conn.setContextId(newId);
modified = true;
} else {
for (Map.Entry<String, String> entry : old2NewMap.entrySet()) {
if (StringUtils.equals(entry.getKey(), ctxId)) {
conn.setContextId(entry.getValue());
modified = true;
}
}
if (!modified) {
throw new Exception("Unhandled case for import: " + item.toString()); //$NON-NLS-1$
}
return modified;
}
private boolean changeRelatedProcess(String newId, String oldId, Item item) throws Exception {
private boolean changeRelatedProcess(Map<String, String> old2NewMap, Item item) throws Exception {
boolean modified = false;
ProcessItem processItem = (ProcessItem) item;
ProcessType processType = processItem.getProcess();
/**
* change context repository id
*/
if (processType != null) {
EList context = processType.getContext();
if (context != null) {
for (Map.Entry<String, String> entry : old2NewMap.entrySet()) {
changeValue(context, entry.getKey(), entry.getValue());
}
modified = true;
}
}
/**
* designerCoreService must not be null
*/
@@ -310,14 +363,18 @@ public class ChangeIdManager {
// }
IContextManager contextManager = process.getContextManager();
if (contextManager != null) {
changeValue(contextManager.getListContext(), oldId, newId);
for (Map.Entry<String, String> entry : old2NewMap.entrySet()) {
changeValue(contextManager.getListContext(), entry.getKey(), entry.getValue());
}
modified = true;
}
/**
* 2. change elementParameters
*/
changeValue(process.getElementParameters(), oldId, newId);
for (Map.Entry<String, String> entry : old2NewMap.entrySet()) {
changeValue(process.getElementParameters(), entry.getKey(), entry.getValue());
}
modified = true;
/**
@@ -329,7 +386,9 @@ public class ChangeIdManager {
while (nodeIter.hasNext()) {
INode node = nodeIter.next();
if (node != null) {
changeParamValueOfNode(node, oldId, newId);
for (Map.Entry<String, String> entry : old2NewMap.entrySet()) {
changeParamValueOfNode(node, entry.getKey(), entry.getValue());
}
}
}
modified = true;
@@ -337,7 +396,7 @@ public class ChangeIdManager {
if (modified) {
if (process instanceof IProcess2) {
ProcessType processType = ((IProcess2) process).saveXmlFile();
processType = ((IProcess2) process).saveXmlFile();
if (item instanceof ProcessItem) {
((ProcessItem) item).setProcess(processType);
} else if (item instanceof JobletProcessItem) {

View File

@@ -182,4 +182,12 @@ FeaturesManager.Type.p2.studioPatch=Studio Patch
FeaturesManager.Type.plainZip=Plain ZIP
FeaturesManager.Category.all=All Categories
P2UpdateManager.update.product=Updating talend product...
P2UpdateManager.p2.uri.null=P2 repository URI is null.
P2UpdateManager.p2.feature.null=Feature list is empty.
P2UpdateManager.no.iu.available=Could not find any available IU in current profile.
P2UpdateManager.user.cancel=User canceled the upgrade of product.
P2UpdateManager.update.error=error updating product : {0}
P2UpdateManager.update.sucess=Update talend product successfully.
UIUtils.exception.interrupt=User cancelled.

View File

@@ -0,0 +1,25 @@
// ============================================================================
//
// Copyright (C) 2006-2019 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.updates.runtime;
public interface P2UpdateConstants {
public static final String STUDIO_CORE_FEATURE_ID = "org.talend.tup.feature.feature.group"; //$NON-NLS-1$
public static final String KEY_UPDATESITE_PATH = "updatesite.path"; //$NON-NLS-1$
public static final String KEY_FEATURES_TO_INSTALL = "features.to.install"; //$NON-NLS-1$
public static final String KEY_FEATURES_TO_UPDATE = "features.to.update"; //$NON-NLS-1$
}

View File

@@ -12,6 +12,8 @@
// ============================================================================
package org.talend.updates.runtime;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
@@ -25,10 +27,14 @@ public class UpdatesRuntimePlugin extends AbstractUIPlugin {
private static UpdatesRuntimePlugin plugin;
private IProvisioningAgent agent;
@SuppressWarnings("restriction")
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
agent = ServiceHelper.getService(context, IProvisioningAgent.class);
}
@Override
@@ -40,4 +46,9 @@ public class UpdatesRuntimePlugin extends AbstractUIPlugin {
public static UpdatesRuntimePlugin getDefault() {
return plugin;
}
public IProvisioningAgent getProvisioningAgent() {
return agent;
}
}

View File

@@ -32,13 +32,11 @@ import org.eclipse.equinox.p2.query.QueryUtil;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.commons.ui.runtime.update.PreferenceKeys;
import org.talend.commons.utils.VersionUtils;
import org.talend.commons.utils.io.FilesUtils;
import org.talend.updates.runtime.i18n.Messages;
@@ -60,8 +58,6 @@ public class P2Manager {
private final Object p2ProfileLock = new Object();
private final Object clearOsgiLock = new Object();
private P2Manager() {
reset();
}
@@ -243,9 +239,4 @@ public class P2Manager {
}
}
public void clearOsgiCache() {
synchronized (clearOsgiLock) {
PlatformUI.getPreferenceStore().setValue(PreferenceKeys.NEED_OSGI_CLEAN, true);
}
}
}

View File

@@ -0,0 +1,273 @@
// ============================================================================
//
// Copyright (C) 2006-2019 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.updates.runtime.engine;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.core.ProvisionException;
import org.eclipse.equinox.p2.engine.IPhaseSet;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.engine.PhaseSetFactory;
import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.operations.InstallOperation;
import org.eclipse.equinox.p2.operations.ProfileModificationJob;
import org.eclipse.equinox.p2.operations.ProvisioningSession;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.equinox.p2.query.QueryUtil;
import org.eclipse.equinox.p2.repository.IRepositoryManager;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.updates.runtime.P2UpdateConstants;
import org.talend.updates.runtime.UpdatesRuntimePlugin;
import org.talend.updates.runtime.i18n.Messages;
import org.talend.updates.runtime.model.ExtraFeatureException;
import org.talend.updates.runtime.model.P2ExtraFeatureException;
import org.talend.updates.runtime.utils.P2UpdateHelper;
public class P2UpdateManager {
private Logger logger = Logger.getLogger(P2UpdateManager.class);
private static P2UpdateManager instance;
private IProvisioningAgent agent;
private ProvisioningSession session;
private IPhaseSet talendPhaseSet;
private P2UpdateManager() {
agent = UpdatesRuntimePlugin.getDefault().getProvisioningAgent();
agent.registerService(IProvisioningAgent.INSTALLER_AGENT, agent);
// DirectorApplication.PROP_P2_PROFILE
agent.registerService("eclipse.p2.profile", IProfileRegistry.SELF);//$NON-NLS-1$
talendPhaseSet = PhaseSetFactory.createDefaultPhaseSetExcluding(new String[] { PhaseSetFactory.PHASE_CHECK_TRUST });
}
public static P2UpdateManager getInstance() {
if (instance == null) {
synchronized (P2UpdateManager.class) {
if (instance == null) {
instance = new P2UpdateManager();
}
}
}
return instance;
}
public IStatus execute(final IProgressMonitor monitor) throws ExtraFeatureException { // check p2 repository url
if (P2UpdateHelper.getP2RepositoryURI() == null) {
return Messages.createErrorStatus(null, "P2UpdateManager.p2.uri.null"); //$NON-NLS-1$
}
// check features to install/update or TODO filter available features in license
List<String> featuresToInstall = P2UpdateHelper.getConfigFeatures(P2UpdateConstants.KEY_FEATURES_TO_INSTALL);
List<String> featuresToUpdate = P2UpdateHelper.getConfigFeatures(P2UpdateConstants.KEY_FEATURES_TO_UPDATE);
if (featuresToInstall.isEmpty() && featuresToUpdate.isEmpty()) {
return Messages.createErrorStatus(null, "P2UpdateManager.p2.feature.null"); //$NON-NLS-1$
}
IStatus result = null;
File configIniBackupFile = null;
try {
// backup the config.ini
configIniBackupFile = P2UpdateHelper.backupConfigFile();
if (!featuresToInstall.isEmpty()) {
result = doInstall(monitor, featuresToInstall);
return result;
}
result = doUpdate(monitor, featuresToUpdate);
} catch (IOException e) {
throw new ExtraFeatureException(
new ProvisionException(Messages.createErrorStatus(e, "ExtraFeaturesFactory.restore.config.error"))); //$NON-NLS-1$
} finally {
boolean success = false;
if (result != null) {
switch (result.getSeverity()) {
case IStatus.OK:
case IStatus.INFO:
case IStatus.WARNING:
success = true;
break;
default:
success = false;
break;
}
}
P2UpdateHelper.clearOsgiCache();
if (success) {
// restore the config.ini
if (configIniBackupFile != null) {
try {
P2UpdateHelper.restoreConfigFile(configIniBackupFile);
} catch (IOException e) {
throw new P2ExtraFeatureException(
new ProvisionException(Messages.createErrorStatus(e, "ExtraFeaturesFactory.back.config.error"))); //$NON-NLS-1$
}
}
if (!featuresToInstall.isEmpty()) {
P2UpdateHelper.clearConfigFeatures(P2UpdateConstants.KEY_FEATURES_TO_INSTALL);
} else if (!featuresToUpdate.isEmpty()) {
P2UpdateHelper.clearConfigFeatures(P2UpdateConstants.KEY_FEATURES_TO_UPDATE);
}
}
}
return result;
}
private IStatus doInstall(IProgressMonitor monitor, List<String> featuresToInstall) throws P2ExtraFeatureException {
SubMonitor subMonitor = SubMonitor.convert(monitor, 4);
subMonitor.setTaskName(Messages.getString("P2UpdateManager.update.product")); //$NON-NLS-1$
// reset isInstalled to make is compute the next time is it used
List<URI> allRepoUris = new ArrayList<>();
allRepoUris.add(P2UpdateHelper.getP2RepositoryURI());
subMonitor.setTaskName(Messages.getString("ExtraFeature.searching.talend.features.label")); //$NON-NLS-1$
Set<IInstallableUnit> availableIUs = queryFromP2Repository(subMonitor.newChild(1), allRepoUris);
// show the installation unit
List<IInstallableUnit> toInstall = availableIUs.stream().filter(iu -> featuresToInstall.contains(iu.getId()))
.collect(Collectors.toList());
logger.debug("IUs to install:" + toInstall); //$NON-NLS-1$
if (toInstall.isEmpty()) {
return Messages.createErrorStatus(null, "P2UpdateManager.no.iu.available");
}
if (subMonitor.isCanceled()) {
return Messages.createCancelStatus("P2UpdateManager.user.cancel"); //$NON-NLS-1$
}
InstallOperation installOperation = new InstallOperation(getProvisioningSession(), toInstall);
IStatus installResolvedStatus = installOperation.resolveModal(subMonitor.newChild(1));
if (installResolvedStatus.getSeverity() == IStatus.ERROR) {
return Messages.createErrorStatus(null, "P2UpdateManager.update.error", //$NON-NLS-1$
installOperation.getResolutionDetails());
}
ProfileModificationJob provisioningJob = (ProfileModificationJob) installOperation
.getProvisioningJob(subMonitor.newChild(1));
if (subMonitor.isCanceled()) {
return Messages.createCancelStatus("P2UpdateManager.user.cancel"); //$NON-NLS-1$
}
provisioningJob.setPhaseSet(talendPhaseSet);
IStatus status = provisioningJob.run(subMonitor.newChild(1));
logger.debug("installed features with status :" + status); //$NON-NLS-1$
return Messages.createOkStatus("P2UpdateManager.update.sucess"); //$NON-NLS-1$
}
private IStatus doUpdate(IProgressMonitor monitor, List<String> featuresToUpdate) throws P2ExtraFeatureException {
SubMonitor subMonitor = SubMonitor.convert(monitor, 5);
subMonitor.setTaskName(Messages.getString("P2UpdateManager.update.product")); //$NON-NLS-1$
// reset isInstalled to make is compute the next time is it used
IProfile p2Profile = getProfile(IProfileRegistry.SELF);
List<URI> allRepoUris = new ArrayList<>();
allRepoUris.add(P2UpdateHelper.getP2RepositoryURI());
Set<IInstallableUnit> currentIUs = p2Profile.query(new UserVisibleRootQuery(), subMonitor.newChild(1))
.toUnmodifiableSet();
// show the installation unit
List<IInstallableUnit> iusToUpdate = currentIUs.stream().filter(iu -> featuresToUpdate.contains(iu.getId()))
.collect(Collectors.toList());
logger.debug("IUs to update:" + iusToUpdate); //$NON-NLS-1$
if (iusToUpdate.isEmpty()) {
return Messages.createErrorStatus(null, "P2UpdateManager.no.iu.available"); //$NON-NLS-1$
}
// update
UpdateOperation updateOperation = new UpdateOperation(getProvisioningSession(), iusToUpdate);
updateOperation.getProvisioningContext().setArtifactRepositories(allRepoUris.toArray(new URI[allRepoUris.size()]));
updateOperation.getProvisioningContext().setMetadataRepositories(allRepoUris.toArray(new URI[allRepoUris.size()]));
updateOperation.setProfileId(IProfileRegistry.SELF);
IStatus result = updateOperation.resolveModal(subMonitor.newChild(1));
if (subMonitor.isCanceled()) {
return Messages.createCancelStatus("P2UpdateManager.user.cancel"); //$NON-NLS-1$
}
if (result.getSeverity() == IStatus.ERROR) {
return Messages.createErrorStatus(null, "P2UpdateManager.update.error", //$NON-NLS-1$
updateOperation.getResolutionDetails());
}
ProfileModificationJob provisioningJob = (ProfileModificationJob) updateOperation
.getProvisioningJob(subMonitor.newChild(1));
if (subMonitor.isCanceled()) {
return Messages.createCancelStatus("P2UpdateManager.user.cancel"); //$NON-NLS-1$
}
if (provisioningJob == null) {
return Messages.createErrorStatus(null, "P2UpdateManager.update.error", //$NON-NLS-1$
updateOperation.getResolutionDetails());
}
provisioningJob.setPhaseSet(talendPhaseSet);
IStatus status = provisioningJob.run(subMonitor.newChild(1));
if (subMonitor.isCanceled()) {
return Messages.createCancelStatus("P2UpdateManager.user.cancel"); //$NON-NLS-1$
}
logger.debug("Updated product with status: " + status); //$NON-NLS-1$
if (featuresToUpdate.contains(P2UpdateConstants.STUDIO_CORE_FEATURE_ID)) {
// TODO change to the new studio.core feature.
try {
P2UpdateHelper.updateProductVersion(subMonitor.newChild(1), getProfile(IProfileRegistry.SELF));
// remove .syncMarker to force to sync maven repository
String filePath = System.getProperty("m2.syncmarker.path"); //$NON-NLS-1$
if (filePath != null) {
File markerFile = new File(filePath);
if (markerFile.exists()) {
markerFile.delete();
}
}
} catch (IOException e) {
ExceptionHandler.process(e);
}
}
return Messages.createOkStatus("P2UpdateManager.update.sucess"); //$NON-NLS-1$
}
public Set<IInstallableUnit> queryFromP2Repository(IProgressMonitor monitor, List<URI> allRepoUris) {
// get the repository managers and add our repository
IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) agent
.getService(IMetadataRepositoryManager.SERVICE_NAME);
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent
.getService(IArtifactRepositoryManager.SERVICE_NAME);
// remove existing repositories
for (URI existingRepUri : metadataManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)) {
metadataManager.removeRepository(existingRepUri);
}
for (URI existingRepUri : artifactManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)) {
metadataManager.removeRepository(existingRepUri);
}
for (URI repoUri : allRepoUris) {
metadataManager.addRepository(repoUri);
artifactManager.addRepository(repoUri);
}
return metadataManager.query(QueryUtil.createLatestQuery(QueryUtil.createIUGroupQuery()), monitor).toUnmodifiableSet();
}
public ProvisioningSession getProvisioningSession() {
if (session == null) {
session = new ProvisioningSession(agent);
}
return session;
}
public IProfileRegistry getProfileRegistry() {
return (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
}
public IProfile getProfile(String profilId) {
return getProfileRegistry().getProfile(profilId);
}
}

View File

@@ -13,7 +13,6 @@
package org.talend.updates.runtime.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -62,9 +61,6 @@ import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.commons.runtime.utils.io.IOUtils;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.services.ICoreTisService;
import org.talend.updates.runtime.engine.P2Manager;
import org.talend.updates.runtime.feature.model.Category;
import org.talend.updates.runtime.feature.model.Type;
@@ -77,6 +73,7 @@ import org.talend.updates.runtime.service.ITaCoKitUpdateService;
import org.talend.updates.runtime.service.ITaCoKitUpdateService.ICarInstallationResult;
import org.talend.updates.runtime.storage.AbstractFeatureStorage;
import org.talend.updates.runtime.storage.IFeatureStorage;
import org.talend.updates.runtime.utils.P2UpdateHelper;
import org.talend.updates.runtime.utils.PathUtils;
import org.talend.updates.runtime.utils.TaCoKitCarUtils;
import org.talend.utils.files.FileUtils;
@@ -284,7 +281,7 @@ public class P2ExtraFeature extends AbstractExtraFeature implements IP2Feature {
try {
if (!isUseLegacyP2Install()) {
// backup the config.ini
configIniBackupFile = backupConfigFile();
configIniBackupFile = P2UpdateHelper.backupConfigFile();
} // else legacy p2 install will update the config.ini
doInstallStatus = installP2(progress, allRepoUris);
if (doInstallStatus == null || !doInstallStatus.isOK()) {
@@ -334,9 +331,9 @@ public class P2ExtraFeature extends AbstractExtraFeature implements IP2Feature {
}
}
// restore the config.ini
if (configIniBackupFile != null) { // must existed backup file.
if (isInstalled && configIniBackupFile != null) { // must existed backup file.
try {
restoreConfigFile(configIniBackupFile, isInstalled);
P2UpdateHelper.restoreConfigFile(configIniBackupFile);
} catch (IOException e) {
throw new P2ExtraFeatureException(
new ProvisionException(Messages.createErrorStatus(e, "ExtraFeaturesFactory.back.config.error"))); //$NON-NLS-1$
@@ -359,7 +356,7 @@ public class P2ExtraFeature extends AbstractExtraFeature implements IP2Feature {
}
protected void afterInstallP2(IProgressMonitor progress, Map<File, File> unzippedPatchMap) throws P2ExtraFeatureException {
P2Manager.getInstance().clearOsgiCache();
P2UpdateHelper.clearOsgiCache();
}
protected void afterRestoreConfigFile(IProgressMonitor progress, Map<File, File> unzippedPatchMap)
@@ -546,6 +543,7 @@ public class P2ExtraFeature extends AbstractExtraFeature implements IP2Feature {
protected void updateRoamingProp(IProvisioningAgent agent, IProvisioningAgentProvider agentProvider)
throws ProvisionException {
agent.registerService(IProvisioningAgent.INSTALLER_AGENT, agentProvider.createAgent(null));
// DirectorApplication.PROP_P2_PROFILE
agent.registerService("eclipse.p2.profile", getP2ProfileId());//$NON-NLS-1$
}
@@ -659,39 +657,6 @@ public class P2ExtraFeature extends AbstractExtraFeature implements IP2Feature {
}
}
protected File backupConfigFile() throws IOException {
try {
File configurationFile = PathUtils.getStudioConfigFile();
File tempFile = File.createTempFile("config.ini", null); //$NON-NLS-1$
FilesUtils.copyFile(new FileInputStream(configurationFile), tempFile);
return tempFile;
} catch (Exception e) {
if (e instanceof IOException) {
throw (IOException) e;
}
throw new IOException(e);
}
}
protected void restoreConfigFile(File toResore, boolean isInstalled) throws IOException {
try {
File configurationFile = PathUtils.getStudioConfigFile();
if (isInstalled && !IOUtils.contentEquals(new FileInputStream(configurationFile), new FileInputStream(toResore))) {
if (GlobalServiceRegister.getDefault().isServiceRegistered(ICoreTisService.class)) {
ICoreTisService coreTisService = (ICoreTisService) GlobalServiceRegister.getDefault()
.getService(ICoreTisService.class);
coreTisService.updateConfiguratorBundles(configurationFile, toResore);
}
}
} catch (Exception e) {
throw new IOException(e);
} finally {
if (toResore != null && toResore.exists()) {
toResore.delete();
}
}
}
@Override
public ExtraFeature getInstalledFeature(IProgressMonitor progress) throws ExtraFeatureException {
ExtraFeature extraFeature = null;

View File

@@ -19,14 +19,18 @@ import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.talend.commons.CommonsPlugin;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.core.nexus.ArtifactRepositoryBean;
import org.talend.core.service.IUpdateService;
import org.talend.updates.runtime.engine.P2UpdateManager;
import org.talend.updates.runtime.engine.component.InstallComponentMessages;
import org.talend.updates.runtime.engine.factory.ComponentsNexusInstallFactory;
import org.talend.updates.runtime.model.ExtraFeature;
import org.talend.updates.runtime.model.ExtraFeatureException;
import org.talend.updates.runtime.model.FeatureCategory;
import org.talend.updates.runtime.nexus.component.NexusServerManager;
@@ -100,4 +104,30 @@ public class UpdateService implements IUpdateService {
}
}
@Override
public boolean checkStudioUpdate(IProgressMonitor monitor) {
if (Platform.inDevelopmentMode()) {
return false;
}
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
IStatus status = P2UpdateManager.getInstance().execute(monitor);
if (status != null) {
switch (status.getSeverity()) {
case IStatus.OK:
case IStatus.INFO:
case IStatus.WARNING:
return true;
default:
return false;
}
}
} catch (ExtraFeatureException e) {
ExceptionHandler.process(e);
}
return false;
}
}

View File

@@ -0,0 +1,158 @@
// ============================================================================
//
// Copyright (C) 2006-2019 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.updates.runtime.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.query.QueryUtil;
import org.eclipse.ui.PlatformUI;
import org.talend.commons.exception.ExceptionHandler;
import org.talend.commons.runtime.utils.io.IOUtils;
import org.talend.commons.ui.runtime.update.PreferenceKeys;
import org.talend.commons.utils.resource.UpdatesHelper;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.runtime.maven.MavenConstants;
import org.talend.core.services.ICoreTisService;
import org.talend.updates.runtime.P2UpdateConstants;
import org.talend.utils.io.FilesUtils;
public class P2UpdateHelper {
private static Object clearOsgiLock = new Object();
public static File backupConfigFile() throws IOException {
try {
File configurationFile = PathUtils.getStudioConfigFile();
File tempFile = File.createTempFile(UpdatesHelper.FILE_CONFIG_INI, null);
FilesUtils.copyFile(new FileInputStream(configurationFile), tempFile);
return tempFile;
} catch (Exception e) {
if (e instanceof IOException) {
throw (IOException) e;
}
throw new IOException(e);
}
}
public static void restoreConfigFile(File toResore) throws IOException {
try {
File configurationFile = PathUtils.getStudioConfigFile();
if (!IOUtils.contentEquals(new FileInputStream(configurationFile), new FileInputStream(toResore))) {
if (GlobalServiceRegister.getDefault().isServiceRegistered(ICoreTisService.class)) {
ICoreTisService coreTisService = (ICoreTisService) GlobalServiceRegister.getDefault()
.getService(ICoreTisService.class);
coreTisService.updateConfiguratorBundles(configurationFile, toResore);
}
}
} catch (Exception e) {
throw new IOException(e);
} finally {
if (toResore != null && toResore.exists()) {
toResore.delete();
}
}
}
public static URI getP2RepositoryURI() {
String updatesite = null;
try (InputStream fis = new FileInputStream(PathUtils.getStudioConfigFile())) {
Properties properties = new Properties();
properties.load(fis);
updatesite = properties.getProperty(P2UpdateConstants.KEY_UPDATESITE_PATH);
} catch (Exception e) {
ExceptionHandler.process(e);
}
if (updatesite == null) {
return null;
}
File file = new File(updatesite);
if (file.isFile() || file.isDirectory()) {
return file.toURI();
}
return URI.create(updatesite);
}
public static List<String> getConfigFeatures(String type) {
String targetFeatures = null;
try (InputStream fis = new FileInputStream(PathUtils.getStudioConfigFile())) {
Properties properties = new Properties();
properties.load(fis);
targetFeatures = properties.getProperty(type);
} catch (Exception e) {
ExceptionHandler.process(e);
}
if (StringUtils.isBlank(targetFeatures)) {
return Collections.emptyList();
}
return Arrays.asList(targetFeatures.trim().split(",")); //$NON-NLS-1$
}
public static void clearConfigFeatures(String type) {
Properties properties = new Properties();
try (InputStream fis = new FileInputStream(PathUtils.getStudioConfigFile())) {
properties.load(fis);
} catch (Exception e) {
ExceptionHandler.process(e);
}
try (OutputStream fos = new FileOutputStream(PathUtils.getStudioConfigFile())) {
properties.setProperty(type, StringUtils.EMPTY);
properties.store(fos, "Configuration File"); //$NON-NLS-1$
} catch (Exception e) {
ExceptionHandler.process(e);
}
}
public static void updateProductVersion(IProgressMonitor monitor, IProfile profile) throws IOException {
Properties properties = new Properties();
File eclipseProductFile = new File(
Platform.getInstallLocation().getDataArea(UpdatesHelper.FILE_ECLIPSE_PRODUCT).getPath());
try (InputStream in = new FileInputStream(eclipseProductFile)) {
properties.load(in);
}
String oldVersion = properties.getProperty("version"); //$NON-NLS-1$
Set<IInstallableUnit> queryResult = profile.query(QueryUtil.createIUQuery(P2UpdateConstants.STUDIO_CORE_FEATURE_ID), monitor)
.toUnmodifiableSet();
IInstallableUnit newCoreFeature = queryResult.stream().findFirst().get();
String newVersion = newCoreFeature.getVersion().toString();
if (oldVersion.endsWith(MavenConstants.SNAPSHOT)) {
// for nightly build only.
newVersion += MavenConstants.SNAPSHOT;
}
properties.setProperty("version", newVersion); //$NON-NLS-1$
try (OutputStream out = new FileOutputStream(eclipseProductFile)) {
properties.store(out, "Configuration File"); //$NON-NLS-1$
}
}
public static void clearOsgiCache() {
synchronized (clearOsgiLock) {
PlatformUI.getPreferenceStore().setValue(PreferenceKeys.NEED_OSGI_CLEAN, true);
}
}
}

View File

@@ -21,8 +21,11 @@ import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.Profile;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
@@ -280,9 +283,43 @@ public class AggregatorPomsHelperTest {
}
};
_helper.updateRefProjectModules(references);
validatePomContent(helper.getProjectRootPom().getLocation().toFile(), defaultProjectGroupId, defaultProjectVersion,
modules);
_helper.updateRefProjectModules(references, new NullProgressMonitor());
validatePomContent(helper.getProjectRootPom().getLocation().toFile(), defaultProjectGroupId, null, defaultProjectVersion,
null, model.getModules(), null);
}
@Test
public void testUpdateRefProjectProfile() throws Exception {
needResetPom = true;
List<ProjectReference> references = new ArrayList<>();
{
ProjectReference reference = PropertiesFactory.eINSTANCE.createProjectReference();
Project project = PropertiesFactory.eINSTANCE.createProject();
project.setTechnicalLabel("TESTPROJECT1");
reference.setReferencedProject(project);
references.add(reference);
}
{
ProjectReference reference = PropertiesFactory.eINSTANCE.createProjectReference();
Project project = PropertiesFactory.eINSTANCE.createProject();
project.setTechnicalLabel("TESTPROJECT2");
reference.setReferencedProject(project);
references.add(reference);
}
AggregatorPomsHelper _helper = new AggregatorPomsHelper() {
@Override
public boolean needUpdateRefProjectModules() {
return true;
}
};
ProjectPreferenceManager preferenceManager = new ProjectPreferenceManager(
ProjectManager.getInstance().getCurrentProject(), DesignerMavenPlugin.PLUGIN_ID, false);
preferenceManager.setValue(MavenConstants.USE_PROFILE_MODULE, true);
_helper.updateRefProjectModules(references, new NullProgressMonitor());
validatePomContent(helper.getProjectRootPom().getLocation().toFile(), defaultProjectGroupId, null, defaultProjectVersion,
null, null, references);
}
/**
@@ -310,17 +347,17 @@ public class AggregatorPomsHelperTest {
// check project pom.
IFile projectPomFile = new AggregatorPomsHelper().getProjectRootPom();
validatePomContent(projectPomFile.getLocation().toFile(), projectGroupId, projectVersion, modules);
validatePomContent(projectPomFile.getLocation().toFile(), projectGroupId, null, projectVersion, null, modules, null);
// check project pom install result.
File installedProjectPom = getInstalledFileFromLocalRepo(projectGroupId,
TalendMavenConstants.DEFAULT_CODE_PROJECT_ARTIFACT_ID, projectVersion, MavenConstants.PACKAGING_POM);
validatePomContent(installedProjectPom, projectGroupId, projectVersion, modules);
validatePomContent(installedProjectPom, projectGroupId, null, projectVersion, null, modules, null);
// check routine pom.
IFile routinePomFile = runProcessService.getTalendCodeJavaProject(ERepositoryObjectType.ROUTINES).getProjectPom();
String routineGroupId = PomIdsHelper.getCodesGroupId("code");
String routineVersion = PomIdsHelper.getCodesVersion();
validatePomContent(routinePomFile.getLocation().toFile(), routineGroupId, routineVersion);
validatePomContent(routinePomFile.getLocation().toFile(), routineGroupId, null, routineVersion, null, null, null);
// check routine install result.
File installedRoutinePom = getInstalledFileFromLocalRepo(routineGroupId,
@@ -329,7 +366,7 @@ public class AggregatorPomsHelperTest {
// check job pom.
IFile jobPomFile = runProcessService.getTalendJobJavaProject(jobProperty).getProjectPom();
validatePomContent(jobPomFile.getLocation().toFile(), jobGroupId, projectGroupId, jobVersion, projectVersion, null);
validatePomContent(jobPomFile.getLocation().toFile(), jobGroupId, projectGroupId, jobVersion, projectVersion, null, null);
}
@Test
@@ -347,19 +384,11 @@ public class AggregatorPomsHelperTest {
IFile jobPomFile = runProcessService.getTalendJobJavaProject(jobProperty).getProjectPom();
validatePomContent(jobPomFile.getLocation().toFile(), customJobGroupId, defaultProjectGroupId, customJobVersion,
defaultProjectVersion, null);
}
private void validatePomContent(File pomFile, String groupId, String version) throws CoreException {
validatePomContent(pomFile, groupId, null, version, null, null);
}
private void validatePomContent(File pomFile, String groupId, String version, List<String> modules) throws CoreException {
validatePomContent(pomFile, groupId, null, version, null, modules);
defaultProjectVersion, null, null);
}
private void validatePomContent(File pomFile, String groupId, String parentGroupId, String version, String parentVersion,
List<String> modules)
List<String> modules, List<ProjectReference> references)
throws CoreException {
Model model = MavenPlugin.getMaven().readModel(pomFile);
assertEquals(groupId, model.getGroupId());
@@ -376,6 +405,24 @@ public class AggregatorPomsHelperTest {
for (String module : modules) {
assertTrue(currentModules.contains(module));
}
} else {
assertEquals(0, model.getModules().stream().filter(module -> module.startsWith("../../")).count());
}
if (references != null) {
if (PomIdsHelper.useProfileModule()) {
List<Profile> refProjectProfiles = model.getProfiles().stream()
.filter(profile -> StringUtils.startsWithIgnoreCase(profile.getId(), projectTechName))
.collect(Collectors.toList());
assertEquals(references.size(), refProjectProfiles.size());
references.forEach(reference -> {
String profileId = (projectTechName + "_" + reference.getReferencedProject().getTechnicalLabel())
.toLowerCase();
assertTrue(refProjectProfiles.stream().anyMatch(profile -> profile.getId().equals(profileId)));
});
}
} else {
assertEquals(0, model.getProfiles().stream().filter(profile -> profile.getId().startsWith(projectTechName)).count());
}
}
@@ -428,6 +475,7 @@ public class AggregatorPomsHelperTest {
projectPreferenceManager.setValue(MavenConstants.PROJECT_VERSION, defaultProjectVersion);
projectPreferenceManager.setValue(MavenConstants.NAME_PUBLISH_AS_SNAPSHOT, defaultUseSnapshot);
projectPreferenceManager.setValue(MavenConstants.POM_FILTER, "");
projectPreferenceManager.setValue(MavenConstants.USE_PROFILE_MODULE, false);
// reset all poms.
if (needResetPom) {
helper.syncAllPomsWithoutProgress(new NullProgressMonitor());