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/griffin/service/src/main/java/org/apache/griffin/core/job
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job/repo/JobInstanceRepo.java
/* 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. */ package org.apache.griffin.core.job.repo; import org.apache.griffin.core.job.entity.JobInstanceBean; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.apache.griffin.core.job.entity.LivySessionStates.State; public interface JobInstanceRepo extends BaseJpaRepository<JobInstanceBean, Long> { JobInstanceBean findByPredicateName(String name); @Query("select s from JobInstanceBean s where s.id = ?1") JobInstanceBean findByInstanceId(Long id); @Query("select s from JobInstanceBean s where s.job.id = ?1") List<JobInstanceBean> findByJobId(Long jobId, Pageable pageable); @Query("select s from JobInstanceBean s where s.job.id = ?1") List<JobInstanceBean> findByJobId(Long jobId); List<JobInstanceBean> findByExpireTmsLessThanEqual(Long expireTms); @Transactional(rollbackFor = Exception.class) @Modifying @Query("delete from JobInstanceBean j " + "where j.expireTms <= ?1 and j.deleted = false ") int deleteByExpireTimestamp(Long expireTms); @Query("select DISTINCT s from JobInstanceBean s where s.state in ?1") List<JobInstanceBean> findByActiveState(State[] states); List<JobInstanceBean> findByTriggerKey(String triggerKey); }
4,100
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job/repo/StreamingJobRepo.java
/* 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. */ package org.apache.griffin.core.job.repo; import org.apache.griffin.core.job.entity.StreamingJob; public interface StreamingJobRepo extends JobRepo<StreamingJob> { }
4,101
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job/repo/BatchJobRepo.java
/* 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. */ package org.apache.griffin.core.job.repo; import org.apache.griffin.core.job.entity.BatchJob; public interface BatchJobRepo extends JobRepo<BatchJob> { }
4,102
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job/factory/AutowiringSpringBeanJobFactory.java
/* 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. */ package org.apache.griffin.core.job.factory; import org.quartz.spi.TriggerFiredBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.scheduling.quartz.SpringBeanJobFactory; /** * Auto-wiring SpringBeanJobFactory is special BeanJobFactory that adds auto-wiring support against * {@link SpringBeanJobFactory} allowing you to inject properties from the scheduler context, job data map * and trigger data entries into the job bean. * * @see SpringBeanJobFactory * @see ApplicationContextAware */ public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private static final Logger LOGGER = LoggerFactory .getLogger(AutowiringSpringBeanJobFactory.class); private transient AutowireCapableBeanFactory beanFactory; @Override public void setApplicationContext(final ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } @Override protected Object createJobInstance(final TriggerFiredBundle bundle) { try { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); return job; } catch (Exception e) { LOGGER.error("fail to create job instance. {}", e); } return null; } }
4,103
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/job/factory/PredicatorFactory.java
/* 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. */ package org.apache.griffin.core.job.factory; import static org.apache.griffin.core.exception.GriffinExceptionMessage.PREDICATE_TYPE_NOT_FOUND; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.griffin.core.exception.GriffinException; import org.apache.griffin.core.job.FileExistPredicator; import org.apache.griffin.core.job.Predicator; import org.apache.griffin.core.job.entity.SegmentPredicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PredicatorFactory { private static final Logger LOGGER = LoggerFactory .getLogger(PredicatorFactory.class); public static Predicator newPredicateInstance(SegmentPredicate segPredicate) { Predicator predicate; switch (segPredicate.getType()) { case "file.exist": predicate = new FileExistPredicator(segPredicate); break; case "custom": predicate = getPredicateBean(segPredicate); break; default: throw new GriffinException.NotFoundException(PREDICATE_TYPE_NOT_FOUND); } return predicate; } private static Predicator getPredicateBean(SegmentPredicate segmentPredicate) { Predicator predicate; String predicateClassName = (String) segmentPredicate.getConfigMap().get("class"); try { Class clazz = Class.forName(predicateClassName); Constructor<Predicator> constructor = clazz.getConstructor(SegmentPredicate.class); predicate = constructor.newInstance(segmentPredicate); } catch (ClassNotFoundException e) { String message = "There is no predicate type that you input."; LOGGER.error(message, e); throw new GriffinException.ServiceException(message, e); } catch (NoSuchMethodException e) { String message = "For predicate with type " + predicateClassName + " constructor with parameter of type " + SegmentPredicate.class.getName() + " not found"; LOGGER.error(message, e); throw new GriffinException.ServiceException(message, e); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { String message = "Error creating predicate bean"; LOGGER.error(message, e); throw new GriffinException.ServiceException(message, e); } return predicate; } }
4,104
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureController.java
/* 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. */ package org.apache.griffin.core.measure; import java.util.List; import javax.validation.Valid; import org.apache.griffin.core.measure.entity.Measure; import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/api/v1") public class MeasureController { @Autowired private MeasureService measureService; @RequestMapping(value = "/measures", method = RequestMethod.GET) public List<? extends Measure> getAllAliveMeasures(@RequestParam(value = "type", defaultValue = "") String type) { return measureService.getAllAliveMeasures(type); } @RequestMapping(value = "/measures/{id}", method = RequestMethod.GET) public Measure getMeasureById(@PathVariable("id") long id) { return measureService.getMeasureById(id); } @RequestMapping(value = "/measures/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteMeasureById(@PathVariable("id") Long id) throws SchedulerException { measureService.deleteMeasureById(id); } @RequestMapping(value = "/measures", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteMeasures() throws SchedulerException { measureService.deleteMeasures(); } @RequestMapping(value = "/measures", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) public Measure updateMeasure(@RequestBody Measure measure) { return measureService.updateMeasure(measure); } @RequestMapping(value = "/measures/owner/{owner}", method = RequestMethod.GET) public List<Measure> getAliveMeasuresByOwner(@PathVariable("owner") @Valid String owner) { return measureService.getAliveMeasuresByOwner(owner); } @RequestMapping(value = "/measures", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public Measure createMeasure(@RequestBody Measure measure) { return measureService.createMeasure(measure); } }
4,105
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/GriffinMeasureOperatorImpl.java
/* 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. */ package org.apache.griffin.core.measure; import static org.apache.griffin.core.util.MeasureUtil.validateMeasure; import org.apache.griffin.core.job.JobServiceImpl; import org.apache.griffin.core.measure.entity.Measure; import org.apache.griffin.core.measure.repo.MeasureRepo; import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("griffinOperation") public class GriffinMeasureOperatorImpl implements MeasureOperator { private final MeasureRepo<Measure> measureRepo; private final JobServiceImpl jobService; @Autowired public GriffinMeasureOperatorImpl(MeasureRepo<Measure> measureRepo, JobServiceImpl jobService) { this.measureRepo = measureRepo; this.jobService = jobService; } @Override public Measure create(Measure measure) { validateMeasure(measure); return measureRepo.save(measure); } @Override public Measure update(Measure measure) { validateMeasure(measure); measure.setDeleted(false); measure = measureRepo.save(measure); return measure; } @Override public void delete(Measure measure) throws SchedulerException { jobService.deleteJobsRelateToMeasure(measure.getId()); measure.setDeleted(true); measureRepo.save(measure); } }
4,106
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureOrgServiceImpl.java
/* 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. */ package org.apache.griffin.core.measure; import static org.apache.griffin.core.exception.GriffinExceptionMessage.ORGANIZATION_NAME_DOES_NOT_EXIST; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.griffin.core.exception.GriffinException; import org.apache.griffin.core.measure.entity.GriffinMeasure; import org.apache.griffin.core.measure.entity.Measure; import org.apache.griffin.core.measure.repo.GriffinMeasureRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MeasureOrgServiceImpl implements MeasureOrgService { @Autowired private GriffinMeasureRepo measureRepo; @Override public List<String> getOrgs() { return measureRepo.findOrganizations(false); } @Override public List<String> getMetricNameListByOrg(String org) { List<String> orgs = measureRepo.findNameByOrganization(org, false); if (CollectionUtils.isEmpty(orgs)) { throw new GriffinException.NotFoundException (ORGANIZATION_NAME_DOES_NOT_EXIST); } return orgs; } @Override public Map<String, List<String>> getMeasureNamesGroupByOrg() { Map<String, List<String>> orgWithMetricsMap = new HashMap<>(); List<GriffinMeasure> measures = measureRepo.findByDeleted(false); for (Measure measure : measures) { String orgName = measure.getOrganization(); orgName = orgName == null ? "null" : orgName; String measureName = measure.getName(); List<String> measureList = orgWithMetricsMap.getOrDefault(orgName, new ArrayList<>()); measureList.add(measureName); orgWithMetricsMap.put(orgName, measureList); } return orgWithMetricsMap; } @Override public Map<String, Map<String, List<Map<String, Object>>>> getMeasureWithJobDetailsGroupByOrg(Map<String, List<Map<String, Object>>> jobDetails) { Map<String, Map<String, List<Map<String, Object>>>> result = new HashMap<>(); List<GriffinMeasure> measures = measureRepo.findByDeleted(false); if (measures == null) { return null; } for (Measure measure : measures) { String orgName = measure.getOrganization(); String measureName = measure.getName(); String measureId = measure.getId().toString(); List<Map<String, Object>> jobList = jobDetails .getOrDefault(measureId, new ArrayList<>()); Map<String, List<Map<String, Object>>> measureWithJobs = result .getOrDefault(orgName, new HashMap<>()); measureWithJobs.put(measureName, jobList); result.put(orgName, measureWithJobs); } return result; } }
4,107
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureService.java
/* 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. */ package org.apache.griffin.core.measure; import java.util.List; import org.apache.griffin.core.measure.entity.Measure; import org.quartz.SchedulerException; public interface MeasureService { List<? extends Measure> getAllAliveMeasures(String type); Measure getMeasureById(long id); void deleteMeasureById(Long id) throws SchedulerException; void deleteMeasures() throws SchedulerException; Measure updateMeasure(Measure measure); List<Measure> getAliveMeasuresByOwner(String owner); Measure createMeasure(Measure measure); }
4,108
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureOrgController.java
/* 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. */ package org.apache.griffin.core.measure; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/api/v1") public class MeasureOrgController { @Autowired private MeasureOrgService measureOrgService; @RequestMapping(value = "/org", method = RequestMethod.GET) public List<String> getOrgs() { return measureOrgService.getOrgs(); } /** * @param org organization name * @return list of metric name, and a metric is the result of executing the * job sharing the same name with measure. */ @RequestMapping(value = "/org/{org}", method = RequestMethod.GET) public List<String> getMetricNameListByOrg(@PathVariable("org") String org) { return measureOrgService.getMetricNameListByOrg(org); } @RequestMapping(value = "/org/measure/names", method = RequestMethod.GET) public Map<String, List<String>> getMeasureNamesGroupByOrg() { return measureOrgService.getMeasureNamesGroupByOrg(); } }
4,109
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureOperator.java
/* 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. */ package org.apache.griffin.core.measure; import org.apache.griffin.core.measure.entity.Measure; import org.quartz.SchedulerException; public interface MeasureOperator { Measure create(Measure measure); Measure update(Measure measure); void delete(Measure measure) throws SchedulerException; }
4,110
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureOrgService.java
/* 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. */ package org.apache.griffin.core.measure; import java.util.List; import java.util.Map; public interface MeasureOrgService { List<String> getOrgs(); List<String> getMetricNameListByOrg(String org); Map<String, List<String>> getMeasureNamesGroupByOrg(); Map<String, Map<String, List<Map<String, Object>>>> getMeasureWithJobDetailsGroupByOrg(Map<String, List<Map<String, Object>>> jobDetailsGroupByMeasure); }
4,111
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/MeasureServiceImpl.java
/* 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. */ package org.apache.griffin.core.measure; import static org.apache.griffin.core.exception.GriffinExceptionMessage.MEASURE_ID_DOES_NOT_EXIST; import static org.apache.griffin.core.exception.GriffinExceptionMessage.MEASURE_NAME_ALREADY_EXIST; import static org.apache.griffin.core.exception.GriffinExceptionMessage.MEASURE_TYPE_DOES_NOT_MATCH; import static org.apache.griffin.core.exception.GriffinExceptionMessage.MEASURE_TYPE_DOES_NOT_SUPPORT; import java.util.List; import org.apache.griffin.core.exception.GriffinException; import org.apache.griffin.core.measure.entity.ExternalMeasure; import org.apache.griffin.core.measure.entity.GriffinMeasure; import org.apache.griffin.core.measure.entity.Measure; import org.apache.griffin.core.measure.repo.ExternalMeasureRepo; import org.apache.griffin.core.measure.repo.GriffinMeasureRepo; import org.apache.griffin.core.measure.repo.MeasureRepo; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; @Service public class MeasureServiceImpl implements MeasureService { private static final Logger LOGGER = LoggerFactory .getLogger(MeasureServiceImpl.class); private static final String GRIFFIN = "griffin"; private static final String EXTERNAL = "external"; @Autowired private MeasureRepo<Measure> measureRepo; @Autowired private GriffinMeasureRepo griffinMeasureRepo; @Autowired private ExternalMeasureRepo externalMeasureRepo; @Autowired @Qualifier("griffinOperation") private MeasureOperator griffinOp; @Autowired @Qualifier("externalOperation") private MeasureOperator externalOp; @Override public List<? extends Measure> getAllAliveMeasures(String type) { if (type.equals(GRIFFIN)) { return griffinMeasureRepo.findByDeleted(false); } else if (type.equals(EXTERNAL)) { return externalMeasureRepo.findByDeleted(false); } return measureRepo.findByDeleted(false); } @Override public Measure getMeasureById(long id) { Measure measure = measureRepo.findByIdAndDeleted(id, false); if (measure == null) { throw new GriffinException .NotFoundException(MEASURE_ID_DOES_NOT_EXIST); } return measure; } @Override public List<Measure> getAliveMeasuresByOwner(String owner) { return measureRepo.findByOwnerAndDeleted(owner, false); } @Override public Measure createMeasure(Measure measure) { List<Measure> aliveMeasureList = measureRepo .findByNameAndDeleted(measure.getName(), false); if (!CollectionUtils.isEmpty(aliveMeasureList)) { LOGGER.warn("Failed to create new measure {}, it already exists.", measure.getName()); throw new GriffinException.ConflictException( MEASURE_NAME_ALREADY_EXIST); } MeasureOperator op = getOperation(measure); return op.create(measure); } @Override public Measure updateMeasure(Measure measure) { Measure m = measureRepo.findByIdAndDeleted(measure.getId(), false); if (m == null) { throw new GriffinException.NotFoundException( MEASURE_ID_DOES_NOT_EXIST); } if (!m.getType().equals(measure.getType())) { LOGGER.warn("Can't update measure to different type."); throw new GriffinException.BadRequestException( MEASURE_TYPE_DOES_NOT_MATCH); } MeasureOperator op = getOperation(measure); return op.update(measure); } @Override public void deleteMeasureById(Long measureId) throws SchedulerException { Measure measure = measureRepo.findByIdAndDeleted(measureId, false); if (measure == null) { throw new GriffinException.NotFoundException( MEASURE_ID_DOES_NOT_EXIST); } MeasureOperator op = getOperation(measure); op.delete(measure); } @Override public void deleteMeasures() throws SchedulerException { List<Measure> measures = measureRepo.findByDeleted(false); for (Measure m : measures) { MeasureOperator op = getOperation(m); op.delete(m); } } private MeasureOperator getOperation(Measure measure) { if (measure instanceof GriffinMeasure) { return griffinOp; } else if (measure instanceof ExternalMeasure) { return externalOp; } throw new GriffinException.BadRequestException( MEASURE_TYPE_DOES_NOT_SUPPORT); } }
4,112
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/ExternalMeasureOperatorImpl.java
/* 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. */ package org.apache.griffin.core.measure; import static org.apache.griffin.core.util.MeasureUtil.validateMeasure; import org.apache.griffin.core.job.entity.VirtualJob; import org.apache.griffin.core.job.repo.VirtualJobRepo; import org.apache.griffin.core.measure.entity.ExternalMeasure; import org.apache.griffin.core.measure.entity.Measure; import org.apache.griffin.core.measure.repo.ExternalMeasureRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component("externalOperation") public class ExternalMeasureOperatorImpl implements MeasureOperator { @Autowired private ExternalMeasureRepo measureRepo; @Autowired private VirtualJobRepo jobRepo; @Override @Transactional public Measure create(Measure measure) { ExternalMeasure em = (ExternalMeasure) measure; validateMeasure(em); em.setVirtualJob(new VirtualJob()); em = measureRepo.save(em); VirtualJob vj = genVirtualJob(em, em.getVirtualJob()); jobRepo.save(vj); return em; } @Override public Measure update(Measure measure) { ExternalMeasure latestMeasure = (ExternalMeasure) measure; validateMeasure(latestMeasure); ExternalMeasure originMeasure = measureRepo.findOne( latestMeasure.getId()); VirtualJob vj = genVirtualJob(latestMeasure, originMeasure.getVirtualJob()); latestMeasure.setVirtualJob(vj); measure = measureRepo.save(latestMeasure); return measure; } @Override public void delete(Measure measure) { ExternalMeasure em = (ExternalMeasure) measure; em.setDeleted(true); em.getVirtualJob().setDeleted(true); measureRepo.save(em); } private VirtualJob genVirtualJob(ExternalMeasure em, VirtualJob vj) { vj.setMeasureId(em.getId()); vj.setJobName(em.getName()); vj.setMetricName(em.getMetricName()); return vj; } }
4,113
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/GriffinMeasure.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.apache.commons.collections.CollectionUtils; import org.apache.griffin.core.util.JsonUtil; import org.springframework.util.StringUtils; /** * Measures processed on Griffin */ @Entity public class GriffinMeasure extends Measure { public enum ProcessType { /** * Currently we just support BATCH and STREAMING type */ BATCH, STREAMING } @Enumerated(EnumType.STRING) private ProcessType processType; private static final long serialVersionUID = -475176898459647661L; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private Long timestamp; @JsonIgnore @Column(length = 1024) private String ruleDescription; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private Map<String, Object> ruleDescriptionMap; @NotNull @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) @JoinColumn(name = "measure_id") private List<DataSource> dataSources = new ArrayList<>(); @NotNull @OneToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) @JoinColumn(name = "evaluate_rule_id") private EvaluateRule evaluateRule; @JsonProperty("process.type") public ProcessType getProcessType() { return processType; } public void setProcessType(ProcessType processType) { this.processType = processType; } @JsonProperty("data.sources") public List<DataSource> getDataSources() { return dataSources; } public void setDataSources(List<DataSource> dataSources) { if (CollectionUtils.isEmpty(dataSources)) { throw new NullPointerException("Data source can not be empty."); } this.dataSources = dataSources; } @JsonProperty("evaluate.rule") public EvaluateRule getEvaluateRule() { return evaluateRule; } public void setEvaluateRule(EvaluateRule evaluateRule) { if (evaluateRule == null || CollectionUtils.isEmpty(evaluateRule .getRules())) { throw new NullPointerException("Evaluate rule can not be empty."); } this.evaluateRule = evaluateRule; } @JsonProperty("rule.description") public Map<String, Object> getRuleDescriptionMap() { return ruleDescriptionMap; } public void setRuleDescriptionMap(Map<String, Object> ruleDescriptionMap) { this.ruleDescriptionMap = ruleDescriptionMap; } private String getRuleDescription() { return ruleDescription; } private void setRuleDescription(String ruleDescription) { this.ruleDescription = ruleDescription; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } @Override public String getType() { return "griffin"; } public GriffinMeasure() { super(); } public GriffinMeasure(String name, String owner, List<DataSource> dataSources, EvaluateRule evaluateRule, List<String> sinksList) { this.name = name; this.owner = owner; this.dataSources = dataSources; this.evaluateRule = evaluateRule; setSinksList(sinksList); } public GriffinMeasure(Long measureId, String name, String owner, List<DataSource> dataSources, EvaluateRule evaluateRule) { this.setId(measureId); this.name = name; this.owner = owner; this.dataSources = dataSources; this.evaluateRule = evaluateRule; } @PrePersist @PreUpdate public void save() throws JsonProcessingException { super.save(); if (ruleDescriptionMap != null) { this.ruleDescription = JsonUtil.toJson(ruleDescriptionMap); } } @PostLoad public void load() throws IOException { super.load(); if (!StringUtils.isEmpty(ruleDescription)) { this.ruleDescriptionMap = JsonUtil.toEntity(ruleDescription, new TypeReference<Map<String, Object>>() { }); } } }
4,114
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/AbstractAuditableEntity.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; /** * AbstractAuditableEntity is base entity class definition in Apache Griffin, all * {@link javax.persistence.Entity} classes should extend it. */ @MappedSuperclass public abstract class AbstractAuditableEntity implements Serializable { private static final long serialVersionUID = 4161638281338218249L; @Id @GeneratedValue(strategy = GenerationType.AUTO) protected Long id; @JsonIgnore private Long createdDate = System.currentTimeMillis(); @JsonIgnore private Timestamp modifiedDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCreatedDate() { return createdDate; } public void setCreatedDate(Long createdDate) { this.createdDate = createdDate; } public Timestamp getModifiedDate() { return modifiedDate; } public void setModifiedDate(Timestamp modifiedDate) { this.modifiedDate = modifiedDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AbstractAuditableEntity other = (AbstractAuditableEntity) obj; if (id == null) { return other.id == null; } else { return id.equals(other.id); } } }
4,115
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/EvaluateRule.java
/* 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. */ package org.apache.griffin.core.measure.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OrderBy; @Entity public class EvaluateRule extends AbstractAuditableEntity { private static final long serialVersionUID = 4240072518233967528L; @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) @JoinColumn(name = "evaluate_rule_id") @OrderBy("id ASC") private List<Rule> rules = new ArrayList<>(); public List<Rule> getRules() { return rules; } public void setRules(List<Rule> rules) { this.rules = rules; } public EvaluateRule() { } public EvaluateRule(List<Rule> rules) { this.rules = rules; } }
4,116
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/DqType.java
/* 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. */ package org.apache.griffin.core.measure.entity; public enum DqType { /** * Currently we support six dimensions of measure. */ ACCURACY, PROFILING, TIMELINESS, UNIQUENESS, COMPLETENESS, CONSISTENCY }
4,117
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/DataConnector.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.apache.griffin.core.job.entity.SegmentPredicate; import org.apache.griffin.core.util.JsonUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @Entity public class DataConnector extends AbstractAuditableEntity { private static final long serialVersionUID = -4748881017029815594L; private final static Logger LOGGER = LoggerFactory .getLogger(DataConnector.class); public enum DataType { /** * There are three data source type which we support now. */ HIVE, KAFKA, AVRO, CUSTOM } @NotNull private String name; @Enumerated(EnumType.STRING) private DataType type; private String version; @JsonInclude(JsonInclude.Include.NON_NULL) private String dataFrameName; @JsonInclude(JsonInclude.Include.NON_NULL) private String dataUnit; @JsonInclude(JsonInclude.Include.NON_NULL) private String dataTimeZone; @JsonIgnore @Transient private String defaultDataUnit = "365000d"; @JsonIgnore @Column(length = 20480) private String config; @Transient private Map<String, Object> configMap; @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) @JoinColumn(name = "data_connector_id") private List<SegmentPredicate> predicates = new ArrayList<>(); @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) @JoinColumn(name = "pre_process_id") @JsonInclude(JsonInclude.Include.NON_NULL) private List<StreamingPreProcess> preProcess; public List<SegmentPredicate> getPredicates() { return predicates; } public void setPredicates(List<SegmentPredicate> predicates) { this.predicates = predicates; } @JsonProperty("pre.proc") public List<StreamingPreProcess> getPreProcess() { return CollectionUtils.isEmpty(preProcess) ? null : preProcess; } public void setPreProcess(List<StreamingPreProcess> preProcess) { this.preProcess = preProcess; } @JsonProperty("config") public Map<String, Object> getConfigMap() { return configMap; } public void setConfigMap(Map<String, Object> configMap) { this.configMap = configMap; } private void setConfig(String config) { this.config = config; } private String getConfig() { return config; } @JsonProperty("dataframe.name") public String getDataFrameName() { return dataFrameName; } public void setDataFrameName(String dataFrameName) { this.dataFrameName = dataFrameName; } @JsonProperty("data.unit") public String getDataUnit() { return dataUnit; } public void setDataUnit(String dataUnit) { this.dataUnit = dataUnit; } @JsonProperty("data.time.zone") public String getDataTimeZone() { return dataTimeZone; } public void setDataTimeZone(String dataTimeZone) { this.dataTimeZone = dataTimeZone; } public String getDefaultDataUnit() { return defaultDataUnit; } public void setDefaultDataUnit(String defaultDataUnit) { this.defaultDataUnit = defaultDataUnit; } public String getName() { return name; } public void setName(String name) { if (StringUtils.isEmpty(name)) { LOGGER.warn("Connector name cannot be empty."); throw new NullPointerException(); } this.name = name; } public DataType getType() { return type; } public void setType(DataType type) { this.type = type; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @PrePersist @PreUpdate public void save() throws JsonProcessingException { if (configMap != null) { this.config = JsonUtil.toJson(configMap); } } @PostLoad public void load() throws IOException { if (!StringUtils.isEmpty(config)) { this.configMap = JsonUtil.toEntity(config, new TypeReference<Map<String, Object>>() { }); } } public DataConnector() { } public DataConnector(String name, DataType type, String version, String config, String dataFrameName) throws IOException { this.name = name; this.type = type; this.version = version; this.config = config; this.configMap = JsonUtil.toEntity(config, new TypeReference<Map<String, Object>>() { }); this.dataFrameName = dataFrameName; } public DataConnector(String name, String dataUnit, Map configMap, List<SegmentPredicate> predicates) { this.name = name; this.dataUnit = dataUnit; this.configMap = configMap; this.predicates = predicates; } @Override public String toString() { return "DataConnector{" + "name=" + name + "type=" + type + ", version='" + version + '\'' + ", config=" + config + '}'; } }
4,118
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/Measure.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.apache.commons.lang.StringUtils; import org.apache.griffin.core.util.JsonUtil; @Entity @Inheritance(strategy = InheritanceType.JOINED) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "measure.type") @JsonSubTypes({ @JsonSubTypes.Type(value = GriffinMeasure.class, name = "griffin"), @JsonSubTypes.Type(value = ExternalMeasure.class, name = "external")}) public abstract class Measure extends AbstractAuditableEntity { private static final long serialVersionUID = -4748881017029815714L; @NotNull protected String name; @JsonInclude(JsonInclude.Include.NON_NULL) protected String owner; @Enumerated(EnumType.STRING) private DqType dqType; @JsonInclude(JsonInclude.Include.NON_NULL) private String description; @JsonInclude(JsonInclude.Include.NON_NULL) private String organization; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private List<String> sinksList = Arrays.asList("ELASTICSEARCH", "HDFS"); @JsonIgnore private String sinks; private boolean deleted = false; public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonProperty("dq.type") public DqType getDqType() { return dqType; } public void setDqType(DqType dqType) { this.dqType = dqType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } @JsonProperty("sinks") public List<String> getSinksList() { return sinksList; } public void setSinksList(List<String> sinksList) { this.sinksList = sinksList; } private String getSinks() { return sinks; } private void setSinks(String sinks) { this.sinks = sinks; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } @PrePersist @PreUpdate public void save() throws JsonProcessingException { if (sinksList != null) { this.sinks = JsonUtil.toJson(sinksList); } } @PostLoad public void load() throws IOException { if (!StringUtils.isEmpty(sinks)) { this.sinksList = JsonUtil.toEntity(sinks, new TypeReference<List<String>>() { }); } } public Measure() { } public Measure(String name, String description, String organization, String owner) { this.name = name; this.description = description; this.organization = organization; this.owner = owner; } @JsonProperty("measure.type") public abstract String getType(); }
4,119
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/StreamingPreProcess.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Transient; import org.apache.griffin.core.util.JsonUtil; import org.springframework.util.StringUtils; @Entity public class StreamingPreProcess extends AbstractAuditableEntity { private static final long serialVersionUID = -7471448761795495384L; private String dslType; private String inDataFrameName; private String outDataFrameName; private String rule; @JsonIgnore @Column(length = 1024) private String details; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private Map<String, Object> detailsMap; @JsonProperty(("dsl.type")) public String getDslType() { return dslType; } public void setDslType(String dslType) { this.dslType = dslType; } @JsonProperty("in.dataframe.name") public String getInDataFrameName() { return inDataFrameName; } public void setInDataFrameName(String inDataFrameName) { this.inDataFrameName = inDataFrameName; } @JsonProperty("out.dataframe.name") public String getOutDataFrameName() { return outDataFrameName; } public void setOutDataFrameName(String outDataFrameName) { this.outDataFrameName = outDataFrameName; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } private String getDetails() { return details; } private void setDetails(String details) { this.details = details; } @JsonProperty("details") public Map<String, Object> getDetailsMap() { return detailsMap; } public void setDetailsMap(Map<String, Object> details) { this.detailsMap = details; } @PrePersist @PreUpdate public void save() throws JsonProcessingException { if (detailsMap != null) { this.details = JsonUtil.toJson(detailsMap); } } @PostLoad public void load() throws IOException { if (!StringUtils.isEmpty(details)) { this.detailsMap = JsonUtil.toEntity(details, new TypeReference<Map<String, Object>>() { }); } } }
4,120
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/Rule.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.util.List; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.apache.commons.lang.StringUtils; import org.apache.griffin.core.util.JsonUtil; @Entity public class Rule extends AbstractAuditableEntity { private static final long serialVersionUID = -143019093509759648L; /** * three type:1.griffin-dsl 2.df-opr 3.spark-sql */ @NotNull private String dslType; @Enumerated(EnumType.STRING) private DqType dqType; @Column(length = 8 * 1024) @NotNull private String rule; @JsonInclude(JsonInclude.Include.NON_NULL) private String inDataFrameName; @JsonInclude(JsonInclude.Include.NON_NULL) private String outDataFrameName; @JsonIgnore @Column(length = 1024) private String details; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private Map<String, Object> detailsMap; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private List<Map<String, Object>> outList; @JsonIgnore @Column(name = "\"out\"") private String out; @JsonInclude(JsonInclude.Include.NON_NULL) private Boolean cache; @JsonProperty("dsl.type") public String getDslType() { return dslType; } public void setDslType(String dslType) { this.dslType = dslType; } @JsonProperty("dq.type") public DqType getDqType() { return dqType; } public void setDqType(DqType dqType) { this.dqType = dqType; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } @JsonProperty("in.dataframe.name") public String getInDataFrameName() { return inDataFrameName; } public void setInDataFrameName(String inDataFrameName) { this.inDataFrameName = inDataFrameName; } @JsonProperty("out.dataframe.name") public String getOutDataFrameName() { return outDataFrameName; } public void setOutDataFrameName(String outDataFrameName) { this.outDataFrameName = outDataFrameName; } @JsonProperty("details") public Map<String, Object> getDetailsMap() { return detailsMap; } public void setDetailsMap(Map<String, Object> detailsMap) { this.detailsMap = detailsMap; } private String getDetails() { return details; } private void setDetails(String details) { this.details = details; } @JsonProperty("out") public List<Map<String, Object>> getOutList() { return outList; } public void setOutList(List<Map<String, Object>> outList) { this.outList = outList; } private String getOut() { return out; } private void setOut(String out) { this.out = out; } public Boolean getCache() { return cache; } public void setCache(Boolean cache) { this.cache = cache; } @PrePersist @PreUpdate public void save() throws JsonProcessingException { if (detailsMap != null) { this.details = JsonUtil.toJson(detailsMap); } if (outList != null) { this.out = JsonUtil.toJson(outList); } } @PostLoad public void load() throws IOException { if (!StringUtils.isEmpty(details)) { this.detailsMap = JsonUtil.toEntity( details, new TypeReference<Map<String, Object>>() { }); } if (!StringUtils.isEmpty(out)) { this.outList = JsonUtil.toEntity( out, new TypeReference<List<Map<String, Object>>>() { }); } } public Rule() { } public Rule(String dslType, DqType dqType, String rule, Map<String, Object> detailsMap) throws JsonProcessingException { this.dslType = dslType; this.dqType = dqType; this.rule = rule; this.detailsMap = detailsMap; this.details = JsonUtil.toJson(detailsMap); } public Rule(String dslType, DqType dqType, String rule, String inDataFrameName, String outDataFrameName, Map<String, Object> detailsMap, List<Map<String, Object>> outList) throws JsonProcessingException { this(dslType, dqType, rule, detailsMap); this.inDataFrameName = inDataFrameName; this.outDataFrameName = outDataFrameName; this.outList = outList; } }
4,121
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/ExternalMeasure.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToOne; import org.apache.griffin.core.job.entity.VirtualJob; /** * Measures to publish metrics that processed externally */ @Entity public class ExternalMeasure extends Measure { private static final long serialVersionUID = -7551493544224747244L; private String metricName; @JsonIgnore @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private VirtualJob virtualJob; public ExternalMeasure() { super(); } public ExternalMeasure(String name, String description, String organization, String owner, String metricName, VirtualJob vj) { super(name, description, organization, owner); this.metricName = metricName; this.virtualJob = vj; } @JsonProperty("metric.name") public String getMetricName() { return metricName; } public void setMetricName(String metricName) { this.metricName = metricName; } public VirtualJob getVirtualJob() { return virtualJob; } public void setVirtualJob(VirtualJob virtualJob) { this.virtualJob = virtualJob; } @Override public String getType() { return "external"; } }
4,122
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/entity/DataSource.java
/* 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. */ package org.apache.griffin.core.measure.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import javax.persistence.*; import org.apache.griffin.core.util.JsonUtil; import org.springframework.util.StringUtils; @Entity public class DataSource extends AbstractAuditableEntity { private static final long serialVersionUID = -4748881017079815794L; private String name; @OneToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) @JoinColumn(name = "data_source_id") private DataConnector connector = new DataConnector(); private boolean baseline = false; @JsonIgnore @Column(length = 1024) private String checkpoint; @Transient @JsonInclude(JsonInclude.Include.NON_NULL) private Map<String, Object> checkpointMap; public String getName() { return name; } public void setName(String name) { this.name = name; } public DataConnector getConnector() { return connector; } public void setConnector(DataConnector connector) { this.connector = connector; } public boolean isBaseline() { return baseline; } public void setBaseline(boolean baseline) { this.baseline = baseline; } private String getCheckpoint() { return checkpoint; } private void setCheckpoint(String checkpoint) { this.checkpoint = checkpoint; } @JsonProperty("checkpoint") public Map<String, Object> getCheckpointMap() { return checkpointMap; } public void setCheckpointMap(Map<String, Object> checkpointMap) { this.checkpointMap = checkpointMap; } @PrePersist @PreUpdate public void save() throws JsonProcessingException { if (checkpointMap != null) { this.checkpoint = JsonUtil.toJson(checkpointMap); } } @PostLoad public void load() throws IOException { if (!StringUtils.isEmpty(checkpoint)) { this.checkpointMap = JsonUtil.toEntity( checkpoint, new TypeReference<Map<String, Object>>() { }); } } public DataSource() { } public DataSource(String name, DataConnector connector) { this.name = name; this.connector = connector; } public DataSource(String name, boolean baseline, Map<String, Object> checkpointMap, DataConnector connector) { this.name = name; this.baseline = baseline; this.checkpointMap = checkpointMap; this.connector = connector; } }
4,123
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/repo/DataConnectorRepo.java
/* 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. */ package org.apache.griffin.core.measure.repo; import java.util.List; import org.apache.griffin.core.measure.entity.DataConnector; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface DataConnectorRepo extends CrudRepository<DataConnector, Long> { @Query("select dc from DataConnector dc where dc.name in ?1") List<DataConnector> findByConnectorNames(List<String> names); }
4,124
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/repo/ExternalMeasureRepo.java
/* 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. */ package org.apache.griffin.core.measure.repo; import org.apache.griffin.core.measure.entity.ExternalMeasure; public interface ExternalMeasureRepo extends MeasureRepo<ExternalMeasure> { }
4,125
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/repo/MeasureRepo.java
/* 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. */ package org.apache.griffin.core.measure.repo; import org.apache.griffin.core.job.repo.BaseJpaRepository; import org.apache.griffin.core.measure.entity.Measure; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * Interface to access measure repository * * @param <T> Measure and its subclass */ public interface MeasureRepo<T extends Measure> extends BaseJpaRepository<T, Long> { /** * search repository by name and deletion state * * @param name query condition * @param deleted query condition * @return measure collection */ List<T> findByNameAndDeleted(String name, Boolean deleted); /** * search repository by deletion state * * @param deleted query condition * @return measure collection */ List<T> findByDeleted(Boolean deleted); /** * search repository by owner and deletion state * * @param owner query condition * @param deleted query condition * @return measure collection */ List<T> findByOwnerAndDeleted(String owner, Boolean deleted); /** * search repository by id and deletion state * * @param id query condition * @param deleted query condition * @return measure collection */ T findByIdAndDeleted(Long id, Boolean deleted); /** * search repository by deletion state * * @param deleted query condition * @return organization collection */ @Query("select DISTINCT m.organization from #{#entityName} m " + "where m.deleted = ?1 and m.organization is not null") List<String> findOrganizations(Boolean deleted); /** * search repository by organization and deletion state * * @param organization query condition * @param deleted query condition * @return organization collection */ @Query("select m.name from #{#entityName} m " + "where m.organization= ?1 and m.deleted= ?2") List<String> findNameByOrganization(String organization, Boolean deleted); }
4,126
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/repo/EvaluateRuleRepo.java
/* 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. */ package org.apache.griffin.core.measure.repo; import org.apache.griffin.core.measure.entity.EvaluateRule; import org.springframework.data.repository.CrudRepository; public interface EvaluateRuleRepo extends CrudRepository<EvaluateRule, Long> { }
4,127
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/measure/repo/GriffinMeasureRepo.java
/* 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. */ package org.apache.griffin.core.measure.repo; import org.apache.griffin.core.measure.entity.GriffinMeasure; public interface GriffinMeasureRepo extends MeasureRepo<GriffinMeasure> { }
4,128
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/MetricStoreImpl.java
/* 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. */ package org.apache.griffin.core.metric; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.griffin.core.metric.model.MetricValue; import org.apache.griffin.core.util.JsonUtil; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.entity.ContentType; import org.apache.http.message.BasicHeader; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; @Component public class MetricStoreImpl implements MetricStore { private static final String INDEX = "griffin"; private static final String TYPE = "accuracy"; private RestClient client; private HttpHeaders responseHeaders; private String urlGet; private String urlDelete; private String urlPost; private ObjectMapper mapper; private String indexMetaData; public MetricStoreImpl(@Value("${elasticsearch.host}") String host, @Value("${elasticsearch.port}") int port, @Value("${elasticsearch.scheme:http}") String scheme, @Value("${elasticsearch.user:}") String user, @Value("${elasticsearch.password:}") String password) { HttpHost httpHost = new HttpHost(host, port, scheme); RestClientBuilder builder = RestClient.builder(httpHost); if (!user.isEmpty() && !password.isEmpty()) { String encodedAuth = buildBasicAuthString(user, password); Header[] requestHeaders = new Header[]{ new BasicHeader(org.apache.http.HttpHeaders.AUTHORIZATION, encodedAuth)}; builder.setDefaultHeaders(requestHeaders); } this.client = builder.build(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); this.responseHeaders = responseHeaders; String urlBase = String.format("/%s/%s", INDEX, TYPE); this.urlGet = urlBase.concat("/_search?filter_path=hits.hits._source"); this.urlPost = urlBase.concat("/_bulk"); this.urlDelete = urlBase.concat("/_delete_by_query"); this.indexMetaData = String.format( "{ \"index\" : { \"_index\" : " + "\"%s\",\"_type\" : \"%s\" } }%n", INDEX, TYPE); this.mapper = new ObjectMapper(); } @Override public List<MetricValue> getMetricValues(String metricName, int from, int size, long tmst) throws IOException { HttpEntity entity = getHttpEntityForSearch(metricName, from, size, tmst); try { Response response = client.performRequest("GET", urlGet, Collections.emptyMap(), entity); return getMetricValuesFromResponse(response); } catch (ResponseException e) { if (e.getResponse().getStatusLine().getStatusCode() == 404) { return Collections.emptyList(); } throw e; } } private HttpEntity getHttpEntityForSearch(String metricName, int from, int size, long tmst) throws JsonProcessingException { Map<String, Object> map = new HashMap<>(); Map<String, Object> queryParam = new HashMap<>(); Map<String, Object> termQuery = Collections.singletonMap("name.keyword", metricName); queryParam.put("filter", Collections.singletonMap("term", termQuery)); Map<String, Object> sortParam = Collections .singletonMap("tmst", Collections.singletonMap("order", "desc")); map.put("query", Collections.singletonMap("bool", queryParam)); map.put("sort", sortParam); map.put("from", from); map.put("size", size); return new NStringEntity(JsonUtil.toJson(map), ContentType.APPLICATION_JSON); } private List<MetricValue> getMetricValuesFromResponse(Response response) throws IOException { List<MetricValue> metricValues = new ArrayList<>(); JsonNode jsonNode = mapper.readTree(EntityUtils.toString(response .getEntity())); if (jsonNode.hasNonNull("hits") && jsonNode.get("hits") .hasNonNull("hits")) { for (JsonNode node : jsonNode.get("hits").get("hits")) { JsonNode sourceNode = node.get("_source"); Map<String, Object> value = JsonUtil.toEntity( sourceNode.get("value").toString(), new TypeReference<Map<String, Object>>() { }); Map<String, Object> meta = JsonUtil.toEntity( Objects.toString(sourceNode.get("metadata"), null), new TypeReference<Map<String, Object>>() { }); MetricValue metricValue = new MetricValue( sourceNode.get("name").asText(), Long.parseLong(sourceNode.get("tmst").asText()), meta, value); metricValues.add(metricValue); } } return metricValues; } @Override public ResponseEntity<?> addMetricValues(List<MetricValue> metricValues) throws IOException { String bulkRequestBody = getBulkRequestBody(metricValues); HttpEntity entity = new NStringEntity(bulkRequestBody, ContentType.APPLICATION_JSON); Response response = client.performRequest("POST", urlPost, Collections.emptyMap(), entity); return getResponseEntityFromResponse(response); } private String getBulkRequestBody(List<MetricValue> metricValues) throws JsonProcessingException { StringBuilder bulkRequestBody = new StringBuilder(); for (MetricValue metricValue : metricValues) { bulkRequestBody.append(indexMetaData); bulkRequestBody.append(JsonUtil.toJson(metricValue)); bulkRequestBody.append(System.lineSeparator()); } return bulkRequestBody.toString(); } @Override public ResponseEntity<?> deleteMetricValues(String metricName) throws IOException { Map<String, Object> param = Collections.singletonMap("query", Collections.singletonMap("term", Collections.singletonMap("name.keyword", metricName))); HttpEntity entity = new NStringEntity( JsonUtil.toJson(param), ContentType.APPLICATION_JSON); Response response = client.performRequest("POST", urlDelete, Collections.emptyMap(), entity); return getResponseEntityFromResponse(response); } private ResponseEntity<?> getResponseEntityFromResponse(Response response) throws IOException { String body = EntityUtils.toString(response.getEntity()); HttpStatus status = HttpStatus.valueOf(response.getStatusLine() .getStatusCode()); return new ResponseEntity<>(body, responseHeaders, status); } private static String buildBasicAuthString(String user, String password) { String auth = user + ":" + password; return String.format("Basic %s", Base64.getEncoder().encodeToString( auth.getBytes())); } @Override public MetricValue getMetric(String applicationId) throws IOException { Response response = client.performRequest( "GET", urlGet, Collections.singletonMap( "q", "metadata.applicationId:" + applicationId)); List<MetricValue> metricValues = getMetricValuesFromResponse(response); return metricValues.get(0); } }
4,129
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/MetricStore.java
/* 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. */ package org.apache.griffin.core.metric; import java.io.IOException; import java.util.List; import org.apache.griffin.core.metric.model.MetricValue; import org.springframework.http.ResponseEntity; public interface MetricStore { List<MetricValue> getMetricValues(String metricName, int from, int size, long tmst) throws IOException; ResponseEntity<?> addMetricValues(List<MetricValue> metricValues) throws IOException; ResponseEntity<?> deleteMetricValues(String metricName) throws IOException; MetricValue getMetric(String applicationId) throws IOException; }
4,130
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/MetricServiceImpl.java
/* 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. */ package org.apache.griffin.core.metric; import static org.apache.griffin.core.exception.GriffinExceptionMessage.INVALID_METRIC_RECORDS_OFFSET; import static org.apache.griffin.core.exception.GriffinExceptionMessage.INVALID_METRIC_RECORDS_SIZE; import static org.apache.griffin.core.exception.GriffinExceptionMessage.INVALID_METRIC_VALUE_FORMAT; import static org.apache.griffin.core.exception.GriffinExceptionMessage.JOB_INSTANCE_NOT_FOUND; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.griffin.core.exception.GriffinException; import org.apache.griffin.core.job.entity.AbstractJob; import org.apache.griffin.core.job.entity.JobInstanceBean; import org.apache.griffin.core.job.repo.JobInstanceRepo; import org.apache.griffin.core.job.repo.JobRepo; import org.apache.griffin.core.measure.entity.Measure; import org.apache.griffin.core.measure.repo.MeasureRepo; import org.apache.griffin.core.metric.model.Metric; import org.apache.griffin.core.metric.model.MetricValue; import org.codehaus.jackson.JsonProcessingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service public class MetricServiceImpl implements MetricService { private static final Logger LOGGER = LoggerFactory .getLogger(MetricServiceImpl.class); @Autowired private MeasureRepo<Measure> measureRepo; @Autowired private JobRepo<AbstractJob> jobRepo; @Autowired private MetricStore metricStore; @Autowired private JobInstanceRepo jobInstanceRepo; @Override public Map<String, List<Metric>> getAllMetrics() { Map<String, List<Metric>> metricMap = new HashMap<>(); List<AbstractJob> jobs = jobRepo.findByDeleted(false); List<Measure> measures = measureRepo.findByDeleted(false); Map<Long, Measure> measureMap = measures.stream().collect(Collectors .toMap(Measure::getId, Function.identity())); Map<Long, List<AbstractJob>> jobMap = jobs.stream().collect(Collectors .groupingBy(AbstractJob::getMeasureId, Collectors.toList())); for (Map.Entry<Long, List<AbstractJob>> entry : jobMap.entrySet()) { Long measureId = entry.getKey(); Measure measure = measureMap.get(measureId); List<AbstractJob> jobList = entry.getValue(); List<Metric> metrics = new ArrayList<>(); for (AbstractJob job : jobList) { List<MetricValue> metricValues = getMetricValues(job .getMetricName(), 0, 300, job.getCreatedDate()); metrics.add(new Metric(job.getMetricName(), measure.getDqType(), measure.getOwner(), metricValues)); } metricMap.put(measure.getName(), metrics); } return metricMap; } @Override public List<MetricValue> getMetricValues(String metricName, int offset, int size, long tmst) { if (offset < 0) { throw new GriffinException.BadRequestException (INVALID_METRIC_RECORDS_OFFSET); } if (size < 0) { throw new GriffinException.BadRequestException (INVALID_METRIC_RECORDS_SIZE); } try { return metricStore.getMetricValues(metricName, offset, size, tmst); } catch (IOException e) { LOGGER.error("Failed to get metric values named {}. {}", metricName, e.getMessage()); throw new GriffinException.ServiceException( "Failed to get metric values", e); } } @SuppressWarnings("rawtypes") @Override public ResponseEntity addMetricValues(List<MetricValue> values) { for (MetricValue value : values) { checkFormat(value); } try { return metricStore.addMetricValues(values); } catch (JsonProcessingException e) { LOGGER.warn("Failed to parse metric value.", e.getMessage()); throw new GriffinException.BadRequestException (INVALID_METRIC_VALUE_FORMAT); } catch (IOException e) { LOGGER.error("Failed to add metric values", e); throw new GriffinException.ServiceException( "Failed to add metric values", e); } } @SuppressWarnings("rawtypes") @Override public ResponseEntity deleteMetricValues(String metricName) { try { return metricStore.deleteMetricValues(metricName); } catch (IOException e) { LOGGER.error("Failed to delete metric values named {}. {}", metricName, e.getMessage()); throw new GriffinException.ServiceException( "Failed to delete metric values.", e); } } @Override public MetricValue findMetric(Long id) { JobInstanceBean jobInstanceBean = jobInstanceRepo.findByInstanceId(id); if (jobInstanceBean == null) { LOGGER.warn("There are no job instances with id {} ", id); throw new GriffinException .NotFoundException(JOB_INSTANCE_NOT_FOUND); } String appId = jobInstanceBean.getAppId(); try { return metricStore.getMetric(appId); } catch (IOException e) { LOGGER.warn("Failed to get metric for applicationId {} ", appId); throw new GriffinException.ServiceException("Failed to find metric", e); } } private void checkFormat(MetricValue value) { if (StringUtils.isBlank(value.getName()) || value.getTmst() == null || MapUtils.isEmpty(value.getValue())) { throw new GriffinException.BadRequestException (INVALID_METRIC_VALUE_FORMAT); } } }
4,131
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/MetricService.java
/* 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. */ package org.apache.griffin.core.metric; import java.util.List; import java.util.Map; import org.apache.griffin.core.metric.model.Metric; import org.apache.griffin.core.metric.model.MetricValue; import org.springframework.http.ResponseEntity; public interface MetricService { Map<String, List<Metric>> getAllMetrics(); List<MetricValue> getMetricValues(String metricName, int offset, int size, long tmst); ResponseEntity addMetricValues(List<MetricValue> values); ResponseEntity<?> deleteMetricValues(String metricName); MetricValue findMetric(Long id); }
4,132
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/MetricController.java
/* 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. */ package org.apache.griffin.core.metric; import java.util.List; import java.util.Map; import org.apache.griffin.core.metric.model.Metric; import org.apache.griffin.core.metric.model.MetricValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1") public class MetricController { @Autowired private MetricService metricService; @RequestMapping(value = "/metrics", method = RequestMethod.GET) public Map<String, List<Metric>> getAllMetrics() { return metricService.getAllMetrics(); } @RequestMapping(value = "/metrics/values", method = RequestMethod.GET) public List<MetricValue> getMetricValues(@RequestParam("metricName") String metricName, @RequestParam("size") int size, @RequestParam(value = "offset", defaultValue = "0") int offset, @RequestParam(value = "tmst", defaultValue = "0") long tmst) { return metricService.getMetricValues(metricName, offset, size, tmst); } @RequestMapping(value = "/metrics/values", method = RequestMethod.POST) public ResponseEntity<?> addMetricValues(@RequestBody List<MetricValue> values) { return metricService.addMetricValues(values); } @RequestMapping(value = "/metrics/values", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<?> deleteMetricValues(@RequestParam("metricName") String metricName) { return metricService.deleteMetricValues(metricName); } @RequestMapping(value = "/metrics/values/{instanceId}", method = RequestMethod.GET) public MetricValue getMetric(@PathVariable("instanceId") Long id) { return metricService.findMetric(id); } }
4,133
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/model/Metric.java
/* 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. */ package org.apache.griffin.core.metric.model; import java.util.List; import org.apache.griffin.core.measure.entity.DqType; public class Metric { private String name; private DqType type; private String owner; private List<MetricValue> metricValues; public Metric() { } public Metric(String name, DqType type, String owner, List<MetricValue> metricValues) { this.name = name; this.type = type; this.owner = owner; this.metricValues = metricValues; } public String getName() { return name; } public void setName(String name) { this.name = name; } public DqType getType() { return type; } public void setType(DqType type) { this.type = type; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public List<MetricValue> getMetricValues() { return metricValues; } public void setMetricValues(List<MetricValue> metricValues) { this.metricValues = metricValues; } }
4,134
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metric/model/MetricValue.java
/* 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. */ package org.apache.griffin.core.metric.model; import java.util.Collections; import java.util.Map; import java.util.Objects; public class MetricValue { private String name; private Long tmst; private Map<String, Object> metadata; private Map<String, Object> value; public MetricValue() { } public MetricValue(String name, Long tmst, Map<String, Object> value) { this.name = name; this.tmst = tmst; this.value = value; this.metadata = Collections.emptyMap(); } public MetricValue(String name, Long tmst, Map<String, Object> metadata, Map<String, Object> value) { this.name = name; this.tmst = tmst; this.metadata = metadata; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getTmst() { return tmst; } public void setTmst(Long tmst) { this.tmst = tmst; } public Map<String, Object> getValue() { return value; } public void setValue(Map<String, Object> value) { this.value = value; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricValue that = (MetricValue) o; return Objects.equals(name, that.name) && Objects.equals(tmst, that.tmst) && Objects.equals(metadata, that.metadata) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(name, tmst, metadata, value); } @Override public String toString() { return String.format( "MetricValue{name=%s, ts=%s, meta=%s, value=%s}", name, tmst, metadata, value); } }
4,135
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/exception/GriffinExceptionMessage.java
/* 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. */ package org.apache.griffin.core.exception; public enum GriffinExceptionMessage { //400, "Bad Request" MEASURE_TYPE_DOES_NOT_MATCH(40001, "Property 'measure.type' does not match" + "the type of measure in request body"), INVALID_CONNECTOR_NAME(40002, "Property 'name' in 'connectors' " + "field is invalid"), MISSING_METRIC_NAME(40003, "Missing property 'metricName'"), INVALID_JOB_NAME(40004, "Property 'job.name' is invalid"), MISSING_BASELINE_CONFIG(40005, "Missing 'as.baseline' config in 'data.segments'"), INVALID_METRIC_RECORDS_OFFSET(40006, "Offset must not be less than zero"), INVALID_METRIC_RECORDS_SIZE(40007, "Size must not be less than zero"), INVALID_METRIC_VALUE_FORMAT(40008, "Metric value format is invalid"), INVALID_MEASURE_ID(40009, "Property 'measure.id' is invalid"), INVALID_CRON_EXPRESSION(40010, "Property 'cron.expression' is invalid"), MEASURE_TYPE_DOES_NOT_SUPPORT(40011, "We don't support such measure type."), JOB_TYPE_DOES_NOT_SUPPORT(40011, "We don't support such job type."), STREAMING_JOB_IS_RUNNING(40012, "There is no need to start again " + "as job is RUNNING."), STREAMING_JOB_IS_STOPPED(40012, "There is no need to stop again " + "as job is STOPPED."), JOB_IS_NOT_SCHEDULED(40013, "The job isn't scheduled."), JOB_IS_NOT_IN_PAUSED_STATUS(40014, "The job isn't in paused status."), JOB_IS_IN_PAUSED_STATUS(40015, "The job is already in paused status."), INVALID_MEASURE_PREDICATE(40016, "The measure predicate is invalid"), //404, "Not Found" MEASURE_ID_DOES_NOT_EXIST(40401, "Measure id does not exist"), JOB_ID_DOES_NOT_EXIST(40402, "Job id does not exist"), JOB_NAME_DOES_NOT_EXIST(40403, "Job name does not exist"), NO_SUCH_JOB_ACTION(40404, "No such job action"), JOB_KEY_DOES_NOT_EXIST(40405, "Job key which consists of " + "group and name does not exist."), ORGANIZATION_NAME_DOES_NOT_EXIST(40406, "Organization name " + "does not exist"), HDFS_FILE_NOT_EXIST(40407, "Hadoop data file not exist"), PREDICATE_TYPE_NOT_FOUND(40408, "Unknown predicate type"), INSTANCE_ID_DOES_NOT_EXIST(40409, "Instance id does not exist"), JOB_INSTANCE_NOT_FOUND(40410, "No job instances with given job instance id found"), //409, "Conflict" MEASURE_NAME_ALREADY_EXIST(40901, "Measure name already exists"), QUARTZ_JOB_ALREADY_EXIST(40902, "Quartz job already exist"); private final int code; private final String message; GriffinExceptionMessage(int code, String message) { this.code = code; this.message = message; } public static GriffinExceptionMessage valueOf(int code) { GriffinExceptionMessage[] messages = values(); int len = values().length; for (int i = 0; i < len; i++) { GriffinExceptionMessage message = messages[i]; if (message.code == code) { return message; } } throw new IllegalArgumentException("No matching constant for [" + code + "]"); } @Override public String toString() { return Integer.toString(code); } public int getCode() { return code; } public String getMessage() { return message; } }
4,136
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/exception/GriffinExceptionHandler.java
/* 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. */ package org.apache.griffin.core.exception; import javax.servlet.http.HttpServletRequest; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class GriffinExceptionHandler { @SuppressWarnings("rawtypes") @ExceptionHandler(GriffinException.ServiceException.class) public ResponseEntity handleGriffinExceptionOfServer( HttpServletRequest request, GriffinException.ServiceException e) { String message = e.getMessage(); Throwable cause = e.getCause(); GriffinExceptionResponse body = new GriffinExceptionResponse( HttpStatus.INTERNAL_SERVER_ERROR, message, request.getRequestURI(), cause.getClass().getName()); return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); } @SuppressWarnings("rawtypes") @ExceptionHandler(GriffinException.class) public ResponseEntity handleGriffinExceptionOfClient( HttpServletRequest request, GriffinException e) { ResponseStatus responseStatus = AnnotationUtils.findAnnotation( e.getClass(), ResponseStatus.class); HttpStatus status = responseStatus.code(); String code = e.getMessage(); GriffinExceptionMessage message = GriffinExceptionMessage .valueOf(Integer.valueOf(code)); GriffinExceptionResponse body = new GriffinExceptionResponse( status, message, request.getRequestURI()); return new ResponseEntity<>(body, status); } }
4,137
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/exception/GriffinExceptionResponse.java
/* 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. */ package org.apache.griffin.core.exception; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.Date; import org.springframework.http.HttpStatus; @JsonInclude(JsonInclude.Include.NON_NULL) public class GriffinExceptionResponse { private Date timestamp = new Date(); private int status; private String error; private String code; private String message; private String exception; private String path; GriffinExceptionResponse(HttpStatus status, GriffinExceptionMessage message, String path) { this.status = status.value(); this.error = status.getReasonPhrase(); this.code = Integer.toString(message.getCode()); this.message = message.getMessage(); this.path = path; } GriffinExceptionResponse(HttpStatus status, String message, String path, String exception) { this.status = status.value(); this.error = status.getReasonPhrase(); this.message = message; this.path = path; this.exception = exception; } public Date getTimestamp() { return timestamp; } public int getStatus() { return status; } public String getError() { return error; } public String getCode() { return code; } public String getMessage() { return message; } public String getPath() { return path; } public String getException() { return exception; } }
4,138
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/exception/GriffinException.java
/* 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. */ package org.apache.griffin.core.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @SuppressWarnings("serial") public abstract class GriffinException extends RuntimeException { GriffinException(String message) { super(message); } GriffinException(String message, Throwable cause) { super(message, cause); } @ResponseStatus(value = HttpStatus.NOT_FOUND) public static class NotFoundException extends GriffinException { public NotFoundException(GriffinExceptionMessage message) { super(message.toString()); } } @ResponseStatus(value = HttpStatus.CONFLICT) public static class ConflictException extends GriffinException { public ConflictException(GriffinExceptionMessage message) { super(message.toString()); } } @ResponseStatus(value = HttpStatus.BAD_REQUEST) public static class BadRequestException extends GriffinException { public BadRequestException(GriffinExceptionMessage message) { super(message.toString()); } } public static class ServiceException extends GriffinException { public ServiceException(String message, Throwable cause) { super(message, cause); } } public static class UnImplementedException extends GriffinException { public UnImplementedException(String message) { super(message); } } }
4,139
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/EventSourceType.java
/* 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. */ package org.apache.griffin.core.event; public enum EventSourceType { JOB, MEASURE }
4,140
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/GriffinEventManager.java
/* 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. */ package org.apache.griffin.core.event; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class GriffinEventManager { @Autowired private ApplicationContext applicationContext; @Value("#{'${internal.event.listeners}'.split(',')}") private Set<String> enabledListeners; private List<GriffinHook> eventListeners; @PostConstruct void initializeListeners() { List<GriffinHook> eventListeners = new ArrayList<>(); applicationContext.getBeansOfType(GriffinHook.class) .forEach((beanName, listener) -> { if (enabledListeners.contains(beanName)) { eventListeners.add(listener); } }); this.eventListeners = eventListeners; } public void notifyListeners(GriffinEvent event) { eventListeners.forEach(listener -> { listener.onEvent(event); }); } }
4,141
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/GriffinAbstractEvent.java
/* 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. */ package org.apache.griffin.core.event; public abstract class GriffinAbstractEvent<T> implements GriffinEvent<T> { private T source; private EventType type; private EventSourceType sourceType; private EventPointcutType pointcutType; public GriffinAbstractEvent(T source, EventType type, EventSourceType sourceType, EventPointcutType pointcutType) { this.source = source; this.type = type; this.sourceType = sourceType; this.pointcutType = pointcutType; } @Override public EventType getType() { return this.type; } @Override public EventPointcutType getPointcut() { return pointcutType; } @Override public EventSourceType getSourceType() { return sourceType; } @Override public T getSource() { return source; } }
4,142
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/GriffinHook.java
/* 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. */ package org.apache.griffin.core.event; import org.apache.griffin.core.exception.GriffinException; /** * The Hook interface for receiving internal events. * The class that is interested in processing an event * implements this interface, and the object created with that * class is registered to griffin, using the configuration. * When the event occurs, that object's <code>onEvent</code> method is * invoked. * * @author Eugene Liu * @since 0.3 */ public interface GriffinHook { /** * Invoked when an action occurs. * * @see GriffinEvent */ void onEvent(GriffinEvent event) throws GriffinException; }
4,143
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/JobEventHook.java
/* 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. */ package org.apache.griffin.core.event; import org.apache.griffin.core.exception.GriffinException; import org.springframework.context.annotation.Configuration; @Configuration(value = "GriffinJobEventHook") public class JobEventHook implements GriffinHook { @Override public void onEvent(GriffinEvent event) throws GriffinException { // This method needs to be reimplemented by event-consuming purpose } }
4,144
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/EventPointcutType.java
/* 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. */ package org.apache.griffin.core.event; public enum EventPointcutType { BEFORE, PENDING, AFTER }
4,145
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/JobEvent.java
/* 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. */ package org.apache.griffin.core.event; import org.apache.griffin.core.job.entity.AbstractJob; public class JobEvent extends GriffinAbstractEvent<AbstractJob> { private JobEvent(AbstractJob source, EventType type, EventSourceType sourceType, EventPointcutType pointcutType) { super(source, type, sourceType, pointcutType); } public static JobEvent yieldJobEventBeforeCreation(AbstractJob source) { return new JobEvent(source, EventType.CREATION_EVENT, EventSourceType.JOB, EventPointcutType.BEFORE); } public static JobEvent yieldJobEventAfterCreation(AbstractJob source) { return new JobEvent(source, EventType.CREATION_EVENT, EventSourceType.JOB, EventPointcutType.AFTER); } public static JobEvent yieldJobEventBeforeRemoval(AbstractJob source) { return new JobEvent(source, EventType.REMOVAL_EVENT, EventSourceType.JOB, EventPointcutType.BEFORE); } public static JobEvent yieldJobEventAfterRemoval(AbstractJob source) { return new JobEvent(source, EventType.REMOVAL_EVENT, EventSourceType.JOB, EventPointcutType.AFTER); } }
4,146
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/EventType.java
/* 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. */ package org.apache.griffin.core.event; public enum EventType { CREATION_EVENT, CHANGE_EVENT, REMOVAL_EVENT }
4,147
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/event/GriffinEvent.java
/* 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. */ package org.apache.griffin.core.event; /** * A semantic event which indicates that a griffin-defined action occurred. * This high-level event is generated by an action (such as an * <code>addJob</code>) when the task-specific action occurs. * The event is passed to every <code>GriffinHook</code> object * that registered to receive such events using configuration. * * @author Eugene Liu * @since 0.3 */ public interface GriffinEvent<T> { /** * @return concrete event type */ EventType getType(); /** * @return concrete event pointcut type */ EventPointcutType getPointcut(); /** * @return concrete event source type */ EventSourceType getSourceType(); /** * The object on which the Event initially occurred. * * @return The object on which the Event initially occurred. */ T getSource(); }
4,148
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/login/LoginServiceLdapImpl.java
/* 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. */ package org.apache.griffin.core.login; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.NoSuchElementException; import javax.naming.AuthenticationException; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import org.apache.commons.lang.StringUtils; import org.apache.griffin.core.login.ldap.SelfSignedSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class LoginServiceLdapImpl implements LoginService { private static final Logger LOGGER = LoggerFactory.getLogger (LoginServiceLdapImpl.class); private static final String LDAP_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; private String url; private String email; private String searchBase; private String searchPattern; private SearchControls searchControls; private boolean sslSkipVerify; private String bindDN; private String bindPassword; public LoginServiceLdapImpl(String url, String email, String searchBase, String searchPattern, boolean sslSkipVerify, String bindDN, String bindPassword) { this.url = url; this.email = email; this.searchBase = searchBase; this.searchPattern = searchPattern; this.sslSkipVerify = sslSkipVerify; this.bindDN = bindDN; this.bindPassword = bindPassword; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); this.searchControls = searchControls; } @Override public ResponseEntity<Map<String, Object>> login(Map<String, String> map) { String username = map.get("username"); String password = map.get("password"); // use separate bind credentials, if bindDN is provided String bindAccount = StringUtils.isEmpty(this.bindDN) ? username : this.bindDN; String bindPassword = StringUtils.isEmpty(this.bindDN) ? password : this.bindPassword; String searchFilter = searchPattern.replace("{0}", username); LdapContext ctx = null; try { ctx = getContextInstance(toPrincipal(bindAccount), bindPassword); NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls); SearchResult userObject = getSingleUser(results); // verify password if different bind user is used if (!StringUtils.equals(username, bindAccount)) { String userDN = getAttributeValue(userObject, "distinguishedName", toPrincipal(username)); checkPassword(userDN, password); } Map<String, Object> message = new HashMap<>(); message.put("ntAccount", username); message.put("fullName", getFullName(userObject, username)); message.put("status", 0); return new ResponseEntity<>(message, HttpStatus.OK); } catch (AuthenticationException e) { LOGGER.warn("User {} failed to login with LDAP auth. {}", username, e.getMessage()); } catch (NamingException e) { LOGGER.warn(String.format("User %s failed to login with LDAP auth.", username), e); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { LOGGER.debug("Failed to close LDAP context", e); } } } return null; } private void checkPassword(String name, String password) throws NamingException { getContextInstance(name, password).close(); } private SearchResult getSingleUser(NamingEnumeration<SearchResult> results) throws NamingException { if (!results.hasMoreElements()) { throw new AuthenticationException("User does not exist or not allowed by search string"); } SearchResult result = results.nextElement(); if (results.hasMoreElements()) { SearchResult second = results.nextElement(); throw new NamingException(String.format("Ambiguous search, found two users: %s, %s", result.getNameInNamespace(), second.getNameInNamespace())); } return result; } private String getAttributeValue(SearchResult searchResult, String key, String defaultValue) throws NamingException { Attributes attrs = searchResult.getAttributes(); if (attrs == null) { return defaultValue; } Attribute attrObj = attrs.get(key); if (attrObj == null) { return defaultValue; } try { return (String) attrObj.get(); } catch (NoSuchElementException e) { return defaultValue; } } private String getFullName(SearchResult searchResult, String ntAccount) { try { String cnName = getAttributeValue(searchResult, "cn", null); if (cnName.indexOf("(") > 0) { return cnName.substring(0, cnName.indexOf("(")); } else { // old behavior ignores CNs without "(" return ntAccount; } } catch (NamingException e) { LOGGER.warn("User {} successfully login with LDAP auth, " + "but failed to get full name.", ntAccount); return ntAccount; } } private String toPrincipal(String ntAccount) { if (ntAccount.toUpperCase().startsWith("CN=")) { return ntAccount; } else { return ntAccount + email; } } private LdapContext getContextInstance(String principal, String password) throws NamingException { Hashtable<String, String> ht = new Hashtable<>(); ht.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_FACTORY); ht.put(Context.PROVIDER_URL, url); ht.put(Context.SECURITY_PRINCIPAL, principal); ht.put(Context.SECURITY_CREDENTIALS, password); if (url.startsWith("ldaps") && sslSkipVerify) { ht.put("java.naming.ldap.factory.socket", SelfSignedSocketFactory.class.getName()); } return new InitialLdapContext(ht, null); } }
4,149
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/login/LoginController.java
/* 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. */ package org.apache.griffin.core.login; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1/login") public class LoginController { @Autowired private LoginService loginService; @RequestMapping(value = "/authenticate", method = RequestMethod.POST) public ResponseEntity<Map<String, Object>> login( @RequestBody Map<String, String> map) { return loginService.login(map); } }
4,150
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/login/LoginServiceDefaultImpl.java
/* 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. */ package org.apache.griffin.core.login; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class LoginServiceDefaultImpl implements LoginService { @Override public ResponseEntity<Map<String, Object>> login(Map<String, String> map) { String username = map.get("username"); if (StringUtils.isBlank(username)) { username = "Anonymous"; } Map<String, Object> message = new HashMap<>(); message.put("ntAccount", username); message.put("fullName", username); message.put("status", 0); return new ResponseEntity<>(message, HttpStatus.OK); } }
4,151
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/login/LoginService.java
/* 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. */ package org.apache.griffin.core.login; import java.util.Map; import org.springframework.http.ResponseEntity; /** * LoginService defines an abstract validation method for login action, you can implement * it to customize authentication business. * * @see org.apache.griffin.core.config.LoginConfig * @see LoginServiceDefaultImpl * @see LoginServiceLdapImpl */ public interface LoginService { ResponseEntity<Map<String, Object>> login(Map<String, String> map); }
4,152
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/login
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/login/ldap/SelfSignedSocketFactory.java
/* 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. */ package org.apache.griffin.core.login.ldap; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.griffin.core.exception.GriffinException; /** * SocketFactory ignoring insecure (self-signed, expired) certificates. * <p> * Maintains internal {@code SSLSocketFactory} configured with {@code NoopTrustManager}. * All SocketFactory methods are proxied to internal SSLSocketFactory instance. * Accepts all client and server certificates, from any issuers. */ public class SelfSignedSocketFactory extends SocketFactory { private SSLSocketFactory sf; private SelfSignedSocketFactory() throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{new NoopTrustManager()}, null); sf = ctx.getSocketFactory(); } /** * Part of SocketFactory contract, used by javax.net internals to create new instance. */ public static SocketFactory getDefault() { try { return new SelfSignedSocketFactory(); } catch (Exception e) { throw new GriffinException.ServiceException("Failed to create socket factory", e); } } /** * Insecure trust manager accepting any client and server certificates. */ public static class NoopTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } } @Override public Socket createSocket() throws IOException { return sf.createSocket(); } @Override public Socket createSocket(String s, int i) throws IOException, UnknownHostException { return sf.createSocket(s, i); } @Override public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException, UnknownHostException { return sf.createSocket(s, i, inetAddress, i1); } @Override public Socket createSocket(InetAddress inetAddress, int i) throws IOException { return sf.createSocket(inetAddress, i); } @Override public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException { return sf.createSocket(inetAddress, i, inetAddress1, i1); } }
4,153
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/kafka/KafkaSchemaController.java
/* 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. */ package org.apache.griffin.core.metastore.kafka; import io.confluent.kafka.schemaregistry.client.rest.entities.Config; import io.confluent.kafka.schemaregistry.client.rest.entities.Schema; import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaString; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1/metadata/kafka") public class KafkaSchemaController { @Autowired KafkaSchemaServiceImpl kafkaSchemaService; @RequestMapping(value = "/schema/{id}", method = RequestMethod.GET) public SchemaString getSchemaString(@PathVariable("id") Integer id) { return kafkaSchemaService.getSchemaString(id); } @RequestMapping(value = "/subject", method = RequestMethod.GET) public Iterable<String> getSubjects() { return kafkaSchemaService.getSubjects(); } @RequestMapping(value = "/versions", method = RequestMethod.GET) public Iterable<Integer> getSubjectVersions( @RequestParam("subject") String subject) { return kafkaSchemaService.getSubjectVersions(subject); } @RequestMapping(value = "/subjectSchema", method = RequestMethod.GET) public Schema getSubjectSchema(@RequestParam("subject") String subject, @RequestParam("version") String version) { return kafkaSchemaService.getSubjectSchema(subject, version); } @RequestMapping(value = "/config", method = RequestMethod.GET) public Config getTopLevelConfig() { return kafkaSchemaService.getTopLevelConfig(); } @RequestMapping(value = "/config/{subject}", method = RequestMethod.GET) public Config getSubjectLevelConfig(@PathVariable("subject") String subject) { return kafkaSchemaService.getSubjectLevelConfig(subject); } }
4,154
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/kafka/KafkaSchemaService.java
/* 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. */ package org.apache.griffin.core.metastore.kafka; import io.confluent.kafka.schemaregistry.client.rest.entities.Config; import io.confluent.kafka.schemaregistry.client.rest.entities.Schema; import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaString; public interface KafkaSchemaService { SchemaString getSchemaString(Integer id); Iterable<String> getSubjects(); Iterable<Integer> getSubjectVersions(String subject); Schema getSubjectSchema(String subject, String version); Config getTopLevelConfig(); Config getSubjectLevelConfig(String subject); }
4,155
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/kafka/KafkaSchemaServiceImpl.java
/* 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. */ package org.apache.griffin.core.metastore.kafka; import java.util.Arrays; import io.confluent.kafka.schemaregistry.client.rest.entities.Config; import io.confluent.kafka.schemaregistry.client.rest.entities.Schema; import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; @Service public class KafkaSchemaServiceImpl implements KafkaSchemaService { private static final Logger log = LoggerFactory .getLogger(KafkaSchemaServiceImpl.class); @Value("${kafka.schema.registry.url}") private String url; RestTemplate restTemplate = new RestTemplate(); private String registryUrl(final String path) { if (StringUtils.hasText(path)) { String usePath = path; if (!path.startsWith("/")) { usePath = "/" + path; } return this.url + usePath; } return ""; } @Override public SchemaString getSchemaString(Integer id) { String path = "/schemas/ids/" + id; String regUrl = registryUrl(path); ResponseEntity<SchemaString> res = restTemplate.getForEntity(regUrl, SchemaString.class); SchemaString result = res.getBody(); return result; } @Override public Iterable<String> getSubjects() { String path = "/subjects"; String regUrl = registryUrl(path); ResponseEntity<String[]> res = restTemplate.getForEntity(regUrl, String[].class); Iterable<String> result = Arrays.asList(res.getBody()); return result; } @Override public Iterable<Integer> getSubjectVersions(String subject) { String path = "/subjects/" + subject + "/versions"; String regUrl = registryUrl(path); ResponseEntity<Integer[]> res = restTemplate.getForEntity(regUrl, Integer[].class); Iterable<Integer> result = Arrays.asList(res.getBody()); return result; } @Override public Schema getSubjectSchema(String subject, String version) { String path = "/subjects/" + subject + "/versions/" + version; String regUrl = registryUrl(path); ResponseEntity<Schema> res = restTemplate.getForEntity(regUrl, Schema.class); Schema result = res.getBody(); return result; } @Override public Config getTopLevelConfig() { String path = "/config"; String regUrl = registryUrl(path); ResponseEntity<Config> res = restTemplate.getForEntity(regUrl, Config.class); Config result = res.getBody(); return result; } @Override public Config getSubjectLevelConfig(String subject) { String path = "/config/" + subject; String regUrl = registryUrl(path); ResponseEntity<Config> res = restTemplate.getForEntity(regUrl, Config.class); Config result = res.getBody(); return result; } }
4,156
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/hive/HiveMetaStoreService.java
/* 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. */ package org.apache.griffin.core.metastore.hive; import java.util.List; import java.util.Map; import org.apache.hadoop.hive.metastore.api.Table; public interface HiveMetaStoreService { Iterable<String> getAllDatabases(); Iterable<String> getAllTableNames(String dbName); Map<String, List<String>> getAllTableNames(); List<Table> getAllTable(String db); Map<String, List<Table>> getAllTable(); Table getTable(String dbName, String tableName); void evictHiveCache(); }
4,157
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/hive/HiveMetaStoreServiceJdbcImpl.java
/* 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. */ package org.apache.griffin.core.metastore.hive; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service @Qualifier(value = "jdbcSvc") @CacheConfig(cacheNames = "jdbcHive", keyGenerator = "cacheKeyGenerator") public class HiveMetaStoreServiceJdbcImpl implements HiveMetaStoreService { private static final Logger LOGGER = LoggerFactory .getLogger(HiveMetaStoreService.class); private static final String SHOW_TABLES_IN = "show tables in "; private static final String SHOW_DATABASE = "show databases"; private static final String SHOW_CREATE_TABLE = "show create table "; @Value("${hive.jdbc.className}") private String hiveClassName; @Value("${hive.jdbc.url}") private String hiveUrl; @Value("${hive.need.kerberos}") private String needKerberos; @Value("${hive.keytab.user}") private String keytabUser; @Value("${hive.keytab.path}") private String keytabPath; private Connection conn; public void setConn(Connection conn) { this.conn = conn; } public void setHiveClassName(String hiveClassName) { this.hiveClassName = hiveClassName; } public void setNeedKerberos(String needKerberos) { this.needKerberos = needKerberos; } public void setKeytabUser(String keytabUser) { this.keytabUser = keytabUser; } public void setKeytabPath(String keytabPath) { this.keytabPath = keytabPath; } @PostConstruct public void init() { if (needKerberos != null && needKerberos.equalsIgnoreCase("true")) { LOGGER.info("Hive need Kerberos Auth."); Configuration conf = new Configuration(); conf.set("hadoop.security.authentication", "Kerberos"); UserGroupInformation.setConfiguration(conf); try { UserGroupInformation.loginUserFromKeytab(keytabUser, keytabPath); } catch (IOException e) { LOGGER.error("Register Kerberos has error. {}", e.getMessage()); } } } @Override @Cacheable(unless = "#result==null") public Iterable<String> getAllDatabases() { return queryHiveString(SHOW_DATABASE); } @Override @Cacheable(unless = "#result==null") public Iterable<String> getAllTableNames(String dbName) { return queryHiveString(SHOW_TABLES_IN + dbName); } @Override @Cacheable(unless = "#result==null") public Map<String, List<String>> getAllTableNames() { // If there has a lots of databases in Hive, this method will lead to Griffin crash Map<String, List<String>> res = new HashMap<>(); for (String dbName : getAllDatabases()) { List<String> list = (List<String>) queryHiveString(SHOW_TABLES_IN + dbName); res.put(dbName, list); } return res; } @Override public List<Table> getAllTable(String db) { return null; } @Override public Map<String, List<Table>> getAllTable() { return null; } @Override @Cacheable(unless = "#result==null") public Table getTable(String dbName, String tableName) { Table result = new Table(); result.setDbName(dbName); result.setTableName(tableName); String sql = SHOW_CREATE_TABLE + dbName + "." + tableName; Statement stmt = null; ResultSet rs = null; StringBuilder sb = new StringBuilder(); try { Class.forName(hiveClassName); if (conn == null) { conn = DriverManager.getConnection(hiveUrl); } LOGGER.info("got connection"); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { String s = rs.getString(1); sb.append(s); } String location = getLocation(sb.toString()); List<FieldSchema> cols = getColums(sb.toString()); StorageDescriptor sd = new StorageDescriptor(); sd.setLocation(location); sd.setCols(cols); result.setSd(sd); } catch (Exception e) { LOGGER.error("Query Hive Table metadata has error. {}", e.getMessage()); } finally { closeConnection(stmt, rs); } return result; } @Scheduled(fixedRateString = "${cache.evict.hive.fixedRate.in.milliseconds}") @CacheEvict( cacheNames = "jdbcHive", allEntries = true, beforeInvocation = true) public void evictHiveCache() { LOGGER.info("Evict hive cache"); } /** * Query Hive for Show tables or show databases, which will return List of String * * @param sql sql string * @return */ private Iterable<String> queryHiveString(String sql) { List<String> res = new ArrayList<>(); Statement stmt = null; ResultSet rs = null; try { Class.forName(hiveClassName); if (conn == null) { conn = DriverManager.getConnection(hiveUrl); } LOGGER.info("got connection"); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { res.add(rs.getString(1)); } } catch (Exception e) { LOGGER.error("Query Hive JDBC has error, {}", e.getMessage()); } finally { closeConnection(stmt, rs); } return res; } private void closeConnection(Statement stmt, ResultSet rs) { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { LOGGER.error("Close JDBC connection has problem. {}", e.getMessage()); } } /** * Get the Hive table location from hive table metadata string * * @param tableMetadata hive table metadata string * @return Hive table location */ public String getLocation(String tableMetadata) { tableMetadata = tableMetadata.toLowerCase(); int index = tableMetadata.indexOf("location"); if (index == -1) { return ""; } int start = tableMetadata.indexOf("\'", index); int end = tableMetadata.indexOf("\'", start + 1); if (start == -1 || end == -1) { return ""; } return tableMetadata.substring(start + 1, end); } /** * Get the Hive table schema: column name, column type, column comment * The input String looks like following: * <p> * CREATE TABLE `employee`( * `eid` int, * `name` string, * `salary` string, * `destination` string) * COMMENT 'Employee details' * ROW FORMAT SERDE * 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' * WITH SERDEPROPERTIES ( * 'field.delim'='\t', * 'line.delim'='\n', * 'serialization.format'='\t') * STORED AS INPUTFORMAT * 'org.apache.hadoop.mapred.TextInputFormat' * OUTPUTFORMAT * 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' * LOCATION * 'file:/user/hive/warehouse/employee' * TBLPROPERTIES ( * 'bucketing_version'='2', * 'transient_lastDdlTime'='1562086077') * * @param tableMetadata hive table metadata string * @return List of FieldSchema */ public List<FieldSchema> getColums(String tableMetadata) { List<FieldSchema> res = new ArrayList<>(); int start = tableMetadata.indexOf("(") + 1; // index of the first '(' int end = tableMetadata.indexOf(")", start); // index of the first ')' String[] colsArr = tableMetadata.substring(start, end).split(","); for (String colStr : colsArr) { colStr = colStr.trim(); String[] parts = colStr.split(" "); String colName = parts[0].trim().substring(1, parts[0].trim().length() - 1); String colType = parts[1].trim(); String comment = getComment(colStr); FieldSchema schema = new FieldSchema(colName, colType, comment); res.add(schema); } return res; } /** * Parse one column string * <p> * Input example: * `merch_date` string COMMENT 'this is merch process date' * * @param colStr column string * @return */ public String getComment(String colStr) { String pattern = "'([^\"|^\']|\"|\')*'"; Matcher m = Pattern.compile(pattern).matcher(colStr.toLowerCase()); if (m.find()) { String text = m.group(); String result = text.substring(1, text.length() - 1); if (!result.isEmpty()) { LOGGER.info("Found value: " + result); } return result; } else { LOGGER.info("NO MATCH"); return ""; } } }
4,158
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/hive/HiveMetaStoreProxy.java
/* 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. */ package org.apache.griffin.core.metastore.hive; import javax.annotation.PreDestroy; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; import org.apache.hadoop.hive.metastore.IMetaStoreClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class HiveMetaStoreProxy { private static final Logger LOGGER = LoggerFactory .getLogger(HiveMetaStoreProxy.class); @Value("${hive.metastore.uris}") private String uris; /** * Set attempts and interval for HiveMetastoreClient to retry. * * @hive.hmshandler.retry.attempts: The number of times to retry a * HMSHandler call if there were a connection error * . * @hive.hmshandler.retry.interval: The time between HMSHandler retry * attempts on failure. */ @Value("${hive.hmshandler.retry.attempts}") private int attempts; @Value("${hive.hmshandler.retry.interval}") private String interval; private IMetaStoreClient client = null; @Bean public IMetaStoreClient initHiveMetastoreClient() { HiveConf hiveConf = new HiveConf(); hiveConf.set("hive.metastore.local", "false"); hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, 3); hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, uris); hiveConf.setIntVar(HiveConf.ConfVars.HMSHANDLERATTEMPTS, attempts); hiveConf.setVar(HiveConf.ConfVars.HMSHANDLERINTERVAL, interval); try { client = HiveMetaStoreClient.newSynchronizedClient(new HiveMetaStoreClient(hiveConf)); } catch (Exception e) { LOGGER.error("Failed to connect hive metastore. {}", e); } return client; } @PreDestroy public void destroy() { if (null != client) { client.close(); } } }
4,159
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/hive/HiveMetaStoreServiceImpl.java
/* 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. */ package org.apache.griffin.core.metastore.hive; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.hive.metastore.IMetaStoreClient; import org.apache.hadoop.hive.metastore.api.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service @Qualifier(value = "metastoreSvc") @CacheConfig(cacheNames = "hive", keyGenerator = "cacheKeyGenerator") public class HiveMetaStoreServiceImpl implements HiveMetaStoreService { private static final Logger LOGGER = LoggerFactory .getLogger(HiveMetaStoreService.class); @Autowired(required = false) private IMetaStoreClient client = null; @Value("${hive.metastore.dbname}") private String defaultDbName; public HiveMetaStoreServiceImpl() { } public void setClient(IMetaStoreClient client) { this.client = client; } @Override @Cacheable(unless = "#result==null") public Iterable<String> getAllDatabases() { Iterable<String> results = null; try { if (client == null) { LOGGER.warn("Hive client is null. " + "Please check your hive config."); return new ArrayList<>(); } results = client.getAllDatabases(); } catch (Exception e) { reconnect(); LOGGER.error("Can not get databases : {}", e); } return results; } @Override @Cacheable(unless = "#result==null") public Iterable<String> getAllTableNames(String dbName) { Iterable<String> results = null; try { if (client == null) { LOGGER.warn("Hive client is null. " + "Please check your hive config."); return new ArrayList<>(); } results = client.getAllTables(getUseDbName(dbName)); } catch (Exception e) { reconnect(); LOGGER.error("Exception fetching tables info: {}", e); return null; } return results; } @Override @Cacheable(unless = "#result==null || #result.isEmpty()") public List<Table> getAllTable(String db) { return getTables(db); } @Override @Cacheable(unless = "#result==null || #result.isEmpty()") public Map<String, List<String>> getAllTableNames() { Map<String, List<String>> result = new HashMap<>(); for (String dbName : getAllDatabases()) { result.put(dbName, Lists.newArrayList(getAllTableNames(dbName))); } return result; } @Override @Cacheable(unless = "#result==null") public Map<String, List<Table>> getAllTable() { Map<String, List<Table>> results = new HashMap<>(); Iterable<String> dbs; // if hive.metastore.uris in application.properties configs wrong, // client will be injected failure and will be null. if (client == null) { LOGGER.warn("Hive client is null. Please check your hive config."); return results; } dbs = getAllDatabases(); if (dbs == null) { return results; } for (String db : dbs) { // TODO: getAllTable() is not reusing caches of getAllTable(db) and vise versa // TODO: getTables() can return empty values on metastore exception results.put(db, getTables(db)); } return results; } @Override @Cacheable(unless = "#result==null") public Table getTable(String dbName, String tableName) { Table result = null; try { if (client == null) { LOGGER.warn("Hive client is null. " + "Please check your hive config."); return null; } result = client.getTable(getUseDbName(dbName), tableName); } catch (Exception e) { reconnect(); LOGGER.error("Exception fetching table info : {}. {}", tableName, e); } return result; } @Scheduled(fixedRateString = "${cache.evict.hive.fixedRate.in.milliseconds}") @CacheEvict( cacheNames = "hive", allEntries = true, beforeInvocation = true) public void evictHiveCache() { LOGGER.info("Evict hive cache"); // TODO: calls within same bean are not cached -- this call is not populating anything // getAllTable(); // LOGGER.info("After evict hive cache, " + // "automatically refresh hive tables cache."); } private List<Table> getTables(String db) { String useDbName = getUseDbName(db); List<Table> allTables = new ArrayList<>(); try { if (client == null) { LOGGER.warn("Hive client is null. " + "Please check your hive config."); return allTables; } Iterable<String> tables = client.getAllTables(useDbName); for (String table : tables) { Table tmp = client.getTable(db, table); allTables.add(tmp); } } catch (Exception e) { reconnect(); LOGGER.error("Exception fetching tables info: {}", e); } return allTables; } private String getUseDbName(String dbName) { if (!StringUtils.hasText(dbName)) { return defaultDbName; } else { return dbName; } } private void reconnect() { try { client.reconnect(); } catch (Exception e) { LOGGER.error("reconnect to hive failed: {}", e); } } }
4,160
0
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore
Create_ds/griffin/service/src/main/java/org/apache/griffin/core/metastore/hive/HiveMetaStoreController.java
/* 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. */ package org.apache.griffin.core.metastore.hive; import java.util.List; import java.util.Map; import org.apache.hadoop.hive.metastore.api.Table; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1/metadata/hive") public class HiveMetaStoreController { @Autowired @Qualifier(value = "metastoreSvc") private HiveMetaStoreService hiveMetaStoreService; @RequestMapping(value = "/dbs", method = RequestMethod.GET) public Iterable<String> getAllDatabases() { return hiveMetaStoreService.getAllDatabases(); } @RequestMapping(value = "/tables/names", method = RequestMethod.GET) public Iterable<String> getAllTableNames(@RequestParam("db") String dbName) { return hiveMetaStoreService.getAllTableNames(dbName); } @RequestMapping(value = "/tables", method = RequestMethod.GET) public List<Table> getAllTables(@RequestParam("db") String dbName) { return hiveMetaStoreService.getAllTable(dbName); } @RequestMapping(value = "/dbs/tables", method = RequestMethod.GET) public Map<String, List<Table>> getAllTables() { return hiveMetaStoreService.getAllTable(); } @RequestMapping(value = "/dbs/tables/names", method = RequestMethod.GET) public Map<String, List<String>> getAllTableNames() { return hiveMetaStoreService.getAllTableNames(); } @RequestMapping(value = "/table", method = RequestMethod.GET) public Table getTable(@RequestParam("db") String dbName, @RequestParam("table") String tableName) { return hiveMetaStoreService.getTable(dbName, tableName); } }
4,161
0
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client/jena/NeptuneJenaSigV4Example.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.neptune.client.jena; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.neptune.auth.NeptuneApacheHttpSigV4Signer; import com.amazonaws.neptune.auth.NeptuneSigV4SignerException; import com.amazonaws.util.StringUtils; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import org.apache.jena.rdfconnection.RDFConnection; import org.apache.jena.rdfconnection.RDFConnectionRemote; import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder; /* * Example of a building a remote connection */ public class NeptuneJenaSigV4Example { public static void main(String... args) throws NeptuneSigV4SignerException { if (args.length == 0 || StringUtils.isNullOrEmpty(args[0])) { System.err.println("Please specify your endpoint as program argument " + "(e.g.: http://<your_neptune_endpoint>:<your_neptune_endpoint>)"); System.exit(1); } final String endpoint = args[0]; final String regionName = "us-east-1"; final AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); final NeptuneApacheHttpSigV4Signer v4Signer = new NeptuneApacheHttpSigV4Signer(regionName, awsCredentialsProvider); final HttpClient v4SigningClient = HttpClientBuilder.create().addInterceptorLast(new HttpRequestInterceptor() { @Override public void process(final HttpRequest req, final HttpContext ctx) throws HttpException { if (req instanceof HttpUriRequest) { final HttpUriRequest httpUriReq = (HttpUriRequest) req; try { v4Signer.signRequest(httpUriReq); } catch (NeptuneSigV4SignerException e) { throw new HttpException("Problem signing the request: ", e); } } else { throw new HttpException("Not an HttpUriRequest"); // this should never happen } } }).build(); RDFConnectionRemoteBuilder builder = RDFConnectionRemote.create() .httpClient(v4SigningClient) .destination(endpoint) // Query only. .queryEndpoint("sparql") .updateEndpoint("sparql"); String query = "SELECT * { ?s ?p ?o } LIMIT 100"; // Whether the connection can be reused depends on the details of the implementation. // See example 5. try (RDFConnection conn = builder.build()) { System.out.println("> Printing query result: "); conn.querySelect(query, System.out::println); } } }
4,162
0
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client/rdf4j/NeptuneSparqlRepository.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.neptune.client.rdf4j; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.neptune.auth.NeptuneApacheHttpSigV4Signer; import com.amazonaws.neptune.auth.NeptuneSigV4Signer; import com.amazonaws.neptune.auth.NeptuneSigV4SignerException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import org.eclipse.rdf4j.repository.sparql.SPARQLRepository; import java.io.IOException; /** * SPARQL repository for connecting to Neptune instances. * * The repository supports both unauthenticated connections as well as IAM using * Signature V4 auth (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). * There are two constructors, one for unauthenticated and one for authenticated connections. * * @author schmdtm */ public class NeptuneSparqlRepository extends SPARQLRepository { /** * URL of the Neptune endpoint (*without* the trailing "/sparql" servlet). */ private final String endpointUrl; /** * The name of the region in which Neptune is running. */ private final String regionName; /** * Whether or not authentication is enabled. */ private final boolean authenticationEnabled; /** * The credentials provider, offering credentials for signing the request. */ private final AWSCredentialsProvider awsCredentialsProvider; /** * The signature V4 signer used to sign the request. */ private NeptuneSigV4Signer<HttpUriRequest> v4Signer; /** * Set up a NeptuneSparqlRepository with V4 signing disabled. * * @param endpointUrl the prefix of the Neptune endpoint (without "/sparql" suffix) */ public NeptuneSparqlRepository(final String endpointUrl) { super(getSparqlEndpoint(endpointUrl)); // all the fields below are only relevant for authentication and can be ignored this.authenticationEnabled = false; this.endpointUrl = null; // only needed if auth is enabled this.awsCredentialsProvider = null; // only needed if auth is enabled this.regionName = null; // only needed if auth is enabled } /** * Set up a NeptuneSparqlRepository with V4 signing enabled. * * @param awsCredentialsProvider the credentials provider used for authentication * @param endpointUrl the prefix of the Neptune endpoint (without "/sparql" suffix) * @param regionName name of the region in which Neptune is running * * @throws NeptuneSigV4SignerException in case something goes wrong with signer initialization */ public NeptuneSparqlRepository( final String endpointUrl, final AWSCredentialsProvider awsCredentialsProvider, final String regionName) throws NeptuneSigV4SignerException { super(getSparqlEndpoint(endpointUrl)); this.authenticationEnabled = true; this.endpointUrl = endpointUrl; this.awsCredentialsProvider = awsCredentialsProvider; this.regionName = regionName; initAuthenticatingHttpClient(); } /** * Wrap the HTTP client to do Signature V4 signing using Apache HTTP's interceptor mechanism. * * @throws NeptuneSigV4SignerException in case something goes wrong with signer initialization */ protected void initAuthenticatingHttpClient() throws NeptuneSigV4SignerException { if (!authenticationEnabled) { return; // auth not initialized, no signing performed } // init an V4 signer for Apache HTTP requests v4Signer = new NeptuneApacheHttpSigV4Signer(regionName, awsCredentialsProvider); /* * Set an interceptor that signs the request before sending it to the server * => note that we add our interceptor last to make sure we operate on the final * version of the request as generated by the interceptor chain */ final HttpClient v4SigningClient = HttpClientBuilder.create().addInterceptorLast(new HttpRequestInterceptor() { @Override public void process(final HttpRequest req, final HttpContext ctx) throws HttpException, IOException { if (req instanceof HttpUriRequest) { final HttpUriRequest httpUriReq = (HttpUriRequest) req; try { v4Signer.signRequest(httpUriReq); } catch (NeptuneSigV4SignerException e) { throw new HttpException("Problem signing the request: ", e); } } else { throw new HttpException("Not an HttpUriRequest"); // this should never happen } } }).build(); setHttpClient(v4SigningClient); } /** * Append the "/sparql" servlet to the endpoint URL. This is fixed, by convention in Neptune. * * @param endpointUrl generic endpoint/server URL * @return the SPARQL endpoint URL for the given server */ private static String getSparqlEndpoint(final String endpointUrl) { return endpointUrl + "/sparql"; } }
4,163
0
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client/rdf4j/NeptuneRdf4JSigV4Example.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.neptune.client.rdf4j; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.neptune.auth.NeptuneSigV4SignerException; import com.amazonaws.util.StringUtils; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.Update; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; /** * Small example demonstrating how to use NeptuneSparqlRepository with SignatureV4 in combination * with the RDF4J library (see http://rdf4j.org/). The example uses the {@link NeptuneSparqlRepository} * class contained in this package, which extends RDF4J's SparqlRepository class by IAM authentication. * <p> * Before running this code, make sure you've got everything setup properly, in particular: * <ol> * <li> Make sure that your AWS credentials are available in the provider chain, see * <a href="https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html"> * DefaultAWSCredentialsProviderChain</a> for more information.</li> * <li> Start the main method by passing in your endpoint, e.g. "http://&lt;my_neptune_host&gt;:&lt;my_neptune_port&gt;". * The server will send a <code>"SELECT * WHERE { ?s ?p ?o } LIMIT 10"</code> query against your endpoint.</li> * </ol> * * @author schmdtm */ public final class NeptuneRdf4JSigV4Example { /** * Region in which the Neptune instance runs. */ private static final String TEST_REGION = "us-east-1"; /** * Sample select query, limited to ten results. */ private static final String SAMPLE_QUERY = "SELECT * WHERE { ?s ?p ?o } LIMIT 10"; /** * Sample SPARQL UPDATE query. */ private static final String SAMPLE_UPDATE = "INSERT DATA { <http://Alice> <http://knows> <http://Bob> }"; /** * Expected exception when sending an unsigned request to an auth enabled neptune server. */ static final String ACCESS_DENIED_MSG = "{\"status\":\"403 Forbidden\",\"message\":\"Access Denied!\"}"; /** * Main method. Expecting the endpoint as the first argument. * * @param args arguments * @throws Exception in case there are problems */ public static void main(final String[] args) throws Exception { if (args.length == 0 || StringUtils.isNullOrEmpty(args[0])) { System.err.println("Please specify your endpoint as program argument " + "(e.g.: http://<my_neptune_host>:<my_neptune_port>)"); System.exit(1); } final String endpoint = args[0]; // example of sending a signed query against the SPARQL endpoint // use default SAMPLE_QUERY if not specified from input args final String query = (args.length > 1 && !StringUtils.isNullOrEmpty(args[1])) ? args[1] : SAMPLE_QUERY; executeSignedQueryRequest(endpoint, query); } /** * Example for signed request. * * @param endpointUrl of the endpoint to which to send the request * @throws NeptuneSigV4SignerException in case there's a problem signing the request */ protected static void executeSignedQueryRequest(final String endpointUrl, final String query) throws NeptuneSigV4SignerException { final AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); final NeptuneSparqlRepository neptuneSparqlRepo = new NeptuneSparqlRepository(endpointUrl, awsCredentialsProvider, TEST_REGION); try { neptuneSparqlRepo.initialize(); evaluateAndPrintQueryResult(query, neptuneSparqlRepo); } finally { neptuneSparqlRepo.shutDown(); } } /** * Example for signed request. * * @param endpointUrl of the endpoint to which to send the request * @throws NeptuneSigV4SignerException in case there's a problem signing the request */ protected static void executeSignedInsertRequest(final String endpointUrl) throws NeptuneSigV4SignerException { final AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); final NeptuneSparqlRepository neptuneSparqlRepo = new NeptuneSparqlRepository(endpointUrl, awsCredentialsProvider, TEST_REGION); try { neptuneSparqlRepo.initialize(); try (RepositoryConnection conn = neptuneSparqlRepo.getConnection()) { final Update update = conn.prepareUpdate(SAMPLE_UPDATE); update.execute(); System.out.println("Update query executed!"); } } finally { neptuneSparqlRepo.shutDown(); } } /** * Example for unsigned request. * * @param endpointUrl of the endpoint to which to send the request */ protected static void executeUnsignedQueryRequest(final String endpointUrl) { // use the simple constructor version which skips auth initialization final NeptuneSparqlRepository neptuneSparqlRepo = new NeptuneSparqlRepository(endpointUrl); try { neptuneSparqlRepo.initialize(); evaluateAndPrintQueryResult(SAMPLE_QUERY, neptuneSparqlRepo); } finally { neptuneSparqlRepo.shutDown(); } } /** * Evaluate the query and print the query result. * * @param queryString the query string to evaluate * @param repo the repository over which to evaluate the query */ protected static void evaluateAndPrintQueryResult(final String queryString, final Repository repo) { try (RepositoryConnection conn = repo.getConnection()) { final TupleQuery query = conn.prepareTupleQuery(queryString); System.out.println("> Printing query result: "); final TupleQueryResult res = query.evaluate(); while (res.hasNext()) { System.err.println("{"); final BindingSet bs = res.next(); boolean first = true; for (final String varName : bs.getBindingNames()) { if (first) { System.out.print(" { "); } else { System.out.print(", "); } System.out.print("?" + varName + " -> " + bs.getBinding(varName)); first = false; } System.out.println("}"); System.out.println("}"); } } } /** * Constructor. */ private NeptuneRdf4JSigV4Example() { } }
4,164
0
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client
Create_ds/amazon-neptune-sparql-java-sigv4/src/main/java/com/amazonaws/neptune/client/rdf4j/package-info.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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. */ /** * RDF4J client examples for Amazon Neptune. */ package com.amazonaws.neptune.client.rdf4j;
4,165
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/ObjectMapperFactory.java
/* * 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. */ package org.apache.directory.scim.spec; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector; import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule; public class ObjectMapperFactory { private final static ObjectMapper objectMapper = createObjectMapper(); public static ObjectMapper getObjectMapper() { return objectMapper; } private static ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.registerModule(new JakartaXmlBindAnnotationModule()); AnnotationIntrospector pair = new AnnotationIntrospectorPair( new JakartaXmlBindAnnotationIntrospector(objectMapper.getTypeFactory()), new JacksonAnnotationIntrospector()); objectMapper.setAnnotationIntrospector(pair); return objectMapper; } }
4,166
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/LuckyNumberExtension.java
/* * 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. */ package org.apache.directory.scim.spec; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema; /** * Allows a User's lucky number to be passed as part of the User's entry via * the SCIM protocol. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" ) @XmlAccessorType(XmlAccessType.NONE) @Data @ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true) public class LuckyNumberExtension implements ScimExtension { public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"; @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true) @XmlElement private long luckyNumber; /** * Provides the URN associated with this extension which, as defined by the * SCIM specification is the extension's unique identifier. * * @return The extension's URN. */ @Override public String getUrn() { return SCHEMA_URN; } }
4,167
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/resources/PhoneNumberBuilderTest.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseException; import org.apache.directory.scim.spec.resources.PhoneNumber.GlobalPhoneNumberBuilder; import org.apache.directory.scim.spec.resources.PhoneNumber.LocalPhoneNumberBuilder; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; public class PhoneNumberBuilderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PhoneNumberBuilderTest.class); private static final String SUBSCRIBER_NUMBER = "subscriberNumber"; private static final String COUNTRY_CODE = "countryCode"; private static final String AREA_CODE = "areaCode"; private static final String EXTENSION = "extension"; private static final String SUBADDRESS = "subAddress"; private static final String GLOBAL_NUMBER = "globalNumber"; private static final String DOMAIN_NAME = "domainName"; private static final String PARAMS_NAME_VALUE = "params names and values"; private static final String FAILURE_MESSAGE = "IllegalArgumentException should have been thrown"; private static final String FAILED_TO_PARSE = "failed to parse"; @SuppressWarnings("unused") private static String[] getInvalidSubscriberNumbers() { return new String[] { null, "", "A", "b", "#1234", "*1234", "@1234", "23 1234", "123 1234", "1234 1234", "123 12345", "123 123 456", "+1-888-888-8888" }; } @SuppressWarnings("unused") private static String[] getValidSubscriberNumbers() { return new String[] { "1", "1234", "12345", "123-1234", "123.1234", "(123)-1234", "(123).1234", "23-1234", "(23)-1234", "(23).1234", "1234-1234", "1234.1234", "(1234)-1234", "(1234).1234", "123-123456", "123.123456", "(123)-123456", "(123).123456", "(123)-123-456", "(123).123.456", "(22).33.44.55", }; } @ParameterizedTest @MethodSource("getInvalidSubscriberNumbers") public void test_invalid_subscriberNumber_for_LocalPhoneNumberBuilder(String invalidSubscriberNumber) throws Exception { assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber(invalidSubscriberNumber).build()) .withMessageContaining(SUBSCRIBER_NUMBER); String temp = invalidSubscriberNumber != null ? (" " + invalidSubscriberNumber + " ") : null; assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber(temp).build()) .withMessageContaining(SUBSCRIBER_NUMBER); } @Test public void test_invalid_padded_subscriberNumber_for_LocalPhoneNumberBuilder() throws Exception { //parameterized value coming into test method has spaces stripped from beginning and end; need to test that spaces are not allowed at all assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber(" 23 ").build()) .withMessageContaining(SUBSCRIBER_NUMBER); } @ParameterizedTest @MethodSource("getValidSubscriberNumbers") public void test_valid_subscriberNumber_for_LocalPhoneNumberBuilder(String validSubscriberNumber) throws Exception { LOGGER.debug("valid subscriber number '{}' start", validSubscriberNumber); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber(validSubscriberNumber).build()) .withMessageContaining(COUNTRY_CODE, "Exception should have been for country code."); } @SuppressWarnings("unused") private static String[] getInvalidCountryCodes() { return new String[] { null, "", "A", "b", "b0", "b01", "b012", "bcd", "bcde", "+0bc", "0ef", "+", "0", "+0", "02", "+03", "056", "+078", "1234", "+1234", "@1234" }; } @SuppressWarnings("unused") private static String[] getValidCountryCodes() { return new String[] { "+1", "1", "+5", "6", "+40", "30", "+995", "995" }; } @ParameterizedTest @MethodSource("getInvalidCountryCodes") public void test_invalid_countryCode_for_LocalPhoneNumberBuilder(String invalidCountryCode) throws Exception { LOGGER.debug("invalid country code '{}' start", invalidCountryCode); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode(invalidCountryCode).build()) .withMessageContaining(COUNTRY_CODE); String temp = invalidCountryCode != null ? (" " + invalidCountryCode + " ") : null; LOGGER.debug("invalid country code '{}' start", temp); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode(temp).build()) .withMessageContaining(COUNTRY_CODE); } @ParameterizedTest @MethodSource("getValidCountryCodes") public void test_valid_countryCode_for_LocalPhoneNumberBuilder(String validCountryCode) throws Exception { LOGGER.debug("valid country code '{}' start", validCountryCode); PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode(validCountryCode).build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertEquals("123-4567", phoneNumber.getNumber()); String countryCode = validCountryCode.startsWith("+") ? validCountryCode : ("+"+validCountryCode); assertEquals(countryCode, phoneNumber.getPhoneContext()); assertEquals(("tel:123-4567;phone-context=" + countryCode), phoneNumber.getValue()); } @SuppressWarnings("unused") private static String[] getInvalidAreaCodes() { return new String[] { "", "A", "b", "b0", "b01", "b012", "bcd", "bcde", "+0bc", "0ef", "+", "@1234" }; } @SuppressWarnings("unused") private static String[] getValidAreaCodes() { return new String[] { "1", "30", "995", "9875" }; } @ParameterizedTest @MethodSource("getInvalidAreaCodes") public void test_invalid_areaCode_for_LocalPhoneNumberBuilder(String invalidAreaCode) throws Exception { LOGGER.debug("invalid area code '{}' start", invalidAreaCode); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode("23").areaCode(invalidAreaCode).build()) .withMessageContaining(AREA_CODE); String temp = invalidAreaCode != null ? (" " + invalidAreaCode + " ") : null; LOGGER.debug("invalid area code '{}' start", temp); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode("23").areaCode(temp).build()) .withMessageContaining(AREA_CODE); } @Test public void test_invalid_padded_areaCode_for_LocalPhoneNumberBuilder() throws Exception { assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode("23").areaCode(" 2 ").build()) .withMessageContaining(AREA_CODE); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode("23").areaCode(" ").build()) .withMessageContaining(AREA_CODE); } @Test public void test_areaCode_can_be_null_for_LocalPhoneNumberBuilder() throws Exception { PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode("23").build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertEquals("123-4567", phoneNumber.getNumber()); assertEquals("+23", phoneNumber.getPhoneContext()); assertEquals("tel:123-4567;phone-context=+23", phoneNumber.getValue()); } @ParameterizedTest @MethodSource("getValidAreaCodes") public void test_valid_areaCode_for_LocalPhoneNumberBuilder(String validAreaCode) throws Exception { LOGGER.debug("valid area code '{}' start", validAreaCode); PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("123-4567").countryCode("23").areaCode(validAreaCode).build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertEquals("123-4567", phoneNumber.getNumber()); assertEquals(("+23-" + validAreaCode), phoneNumber.getPhoneContext()); assertEquals(("tel:123-4567;phone-context=+23-"+validAreaCode), phoneNumber.getValue()); } @SuppressWarnings("unused") private static String[] getInvalidGlobalNumbers() { return new String[] { null, "", "A", "b", "#1234", "*1234", "@1234", "23 1234", "123 1234", "1234 1234", "123 12345", "123 123 456", "+1 888 888 8888" }; } @SuppressWarnings("unused") private static String[] getValidGlobalNumbers() { return new String[] { "+44-20-1234-5678",//global with visualSeparator - "+44.20.1234.5678",//global with visualSeparator . "+1-201-555-0123",//US global format with visualSeparator - "+1.201.555.0123",//US global format with visualSeparator . "+1(201)555.0123",//US global format with visualSeparator . and () "+1(201)555-0123",//US global format with visualSeparator - and () "+880-23-6666-7410",//Bangladesh "+886-912-345678",//Taiwan mobile "+674-556-7815",//Nauru, Oman "+676-27-987",//Tonga "+683-5791",//Niue & Tokelau "+686-22910",//Kiribati "+32-2-555-12-12", //Belguim big city "+32-71-123-456", //Belguim small city "+32-478-12-34-56", //Belguim mobile "+30-21-2-228-4931", //Greece "+352-79-0000", //Luxemburg "+352-2679-0000", "+352-4-000-00", "+970-08-240-7851",//Palestine "+970-059-240-7851",//Palestine mobile "+998-7071-123456789",//Uzbekistan "+998-7071-12345678", "+998-7071-1234567", "+998-74-123456789", "+998-751-12345678", "+998-62-1234567", "+996-312-123456",//Kyrgyzstan "+359-2-912-4501",//Bulgaria "+359-37-9873-571",//Bulgaria mobile "+358-9-333-444",//Finland "+358-045-123-45", //Finland mobile "+358-050-123-45-6", //Finland mobile "+358-045-123-45-67", //Finland mobile "+357-22-123456",//Cyprus "+357-9-987456",//Cyprus mobile "+44-28-9034-0812", //Northern Ireland "+44-7333-187-891", //Nothern Ireland mobile "+351-12-241-6789", //Portugal "+351-90-288-6789", //Portugal mobile "+506-5710-9874", //Costa Rica "+66-2-2134567", //Thailand "+66-44-2134567", //Thailand "+66-080-6345678", //Thailand mobile "+673-215-9642", //Brunei "+386-1-019-45-12",//Slovenia "+386-1-030-99-35",//Slovenia mobile "+7-499-123-78-56", //Russia "+52-744-235-4410",//Mexico "+52-55-235-4410",//Mexico "+855-23-430715", //Cambodia "+855-23-4307159", //Cambodia "+855-76-234-5678", //Cambodia mobile "+86-123-4567-8901", //China mobile "+86-852-123-4567", //China landline "+86-85-1234-5678", //China landline "+852-145-6789-0123", //China mobile "+852-852-123-4567", //China landline "+852-85-1234-5678", //China landline "+886-198-6541-2579", //China mobile "+886-852-123-4567", //China landline "+886-85-1234-5678", //China landline "+977-10-512-345", //Napal "+373-24-91-13-20", //Moldova "+33-03-71-13-20-43", //France "+43-(08)-9345-6765",//Austrailia +43 "+49(05236)-5217775",//Germany +49 "+49(032998)-651224", "+49(065)-51140357", "+81-004-477-3632",//Japan "+81-044-021-3258", "+81-005-920-5122", "+44-(026)-6987-1101",//UK "+44-055-6956-7230", "+44-(0117)-204-2623", "+44-07624-958791", "+1-(495)-172-7974",//Canada "+1-376-597-9524" }; } @ParameterizedTest @MethodSource("getInvalidGlobalNumbers") public void test_invalid_globalNumber_for_GlobalPhoneNumberBuilder(String invalidGlobalNumber) throws Exception { LOGGER.debug("invalid global number '{}' start", invalidGlobalNumber); assertThatIllegalArgumentException() .isThrownBy(() -> new GlobalPhoneNumberBuilder().globalNumber(invalidGlobalNumber).build()) .withMessageContaining(GLOBAL_NUMBER); String temp = invalidGlobalNumber != null ? (" " + invalidGlobalNumber + " ") : null; LOGGER.debug("invalid global number '{}' start", temp); assertThatIllegalArgumentException() .isThrownBy(() -> new GlobalPhoneNumberBuilder().globalNumber(temp).build()) .withMessageContaining(GLOBAL_NUMBER); } @Test public void test_invalid_padded_gloablNumber_for_GlobalPhoneNumberBuilder() throws Exception { //parameterized value coming into test method has spaces stripped from beginning and end; need to test that spaces are not allowed at all assertThatIllegalArgumentException() .isThrownBy(() -> new GlobalPhoneNumberBuilder().globalNumber(" 23 ").build()) .withMessageContaining(GLOBAL_NUMBER); } @ParameterizedTest @MethodSource("getValidGlobalNumbers") public void test_valid_globalNumber_for_GlobalPhoneNumberBuilder(String validGlobalNumber) throws Exception { LOGGER.debug("valid global number '{}' start", validGlobalNumber); PhoneNumber phoneNumber = new GlobalPhoneNumberBuilder().globalNumber(validGlobalNumber).build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertNull(phoneNumber.getPhoneContext(), "PhoneContext should be null"); assertEquals(validGlobalNumber, phoneNumber.getNumber()); assertEquals(("tel:"+validGlobalNumber), phoneNumber.getValue()); } @ParameterizedTest @MethodSource("getValidGlobalNumbers") public void test_valid_noPlusSymbol_globalNumber_for_GlobalPhoneNumberBuilder(String validGlobalNumber) throws Exception { String temp = validGlobalNumber.replace("+", ""); LOGGER.debug("valid global number '{}' start", temp); PhoneNumber phoneNumber = new GlobalPhoneNumberBuilder().globalNumber(temp).build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertNull(phoneNumber.getPhoneContext(), "PhoneContext should be null"); assertEquals("+" + temp, phoneNumber.getNumber()); assertEquals(("tel:+" + temp), phoneNumber.getValue()); } @SuppressWarnings("unused") private static String[] getInvalidDomainNames() { return new String[] { "#1", "*1", "@1", "example com", "hhh@example.com", "EXAMPLE COM", "HHH@EXAMPLE.COM", "eXAmpLE Com2", "hhH@ExaMPlE.CoM2" }; } @SuppressWarnings("unused") private static String[] getValidDomainNames() { return new String[] { "google.com", "2xkcd-ex.com", "Ab0c1d2e3f4g5H6i7-J8K9l0m.org", "Ab0c1d2e3f4g5H6i7-J8K9l0m" }; } @ParameterizedTest @MethodSource("getInvalidDomainNames") public void test_invalid_domainName_for_LocalPhoneNumberBuilder(String invalidDomainName) throws Exception { LOGGER.debug("invalid domain name '{}' start", invalidDomainName); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName(invalidDomainName).build()) .withMessageContaining(DOMAIN_NAME); String temp = invalidDomainName != null ? (" " + invalidDomainName + " ") : null; LOGGER.debug("invalid domain name '{}' start", temp); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName(temp).build()) .withMessageContaining(DOMAIN_NAME); } @Test public void test_invalid_padded_domainName_for_LocalPhoneNumberBuilder() throws Exception { //parameterized value coming into test method has spaces stripped from beginning and end; need to test that spaces are not allowed at all assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName(" 23 ").build()) .withMessageContaining(DOMAIN_NAME); } @Test public void test_no_domainName_coutryCode_or_areaCode_for_LocalPhoneNumberBuilder() throws Exception { assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName(null).build()) .withMessageContaining(DOMAIN_NAME) .withMessageContaining(COUNTRY_CODE); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName("").build()) .withMessageContaining(DOMAIN_NAME) .withMessageContaining(COUNTRY_CODE); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName(" ").build()) .withMessageContaining(DOMAIN_NAME) .withMessageContaining(COUNTRY_CODE); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("222-1707").build()) .withMessageContaining(DOMAIN_NAME) .withMessageContaining(COUNTRY_CODE); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("222-1707").countryCode("").areaCode("").build()) .withMessageContaining(DOMAIN_NAME) .withMessageContaining(COUNTRY_CODE); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("222-1707").countryCode(" ").areaCode(" ").build()) .withMessageContaining(DOMAIN_NAME) .withMessageContaining(COUNTRY_CODE); } @ParameterizedTest @MethodSource("getValidDomainNames") public void test_valid_domainName_for_LocalPhoneNumberBuilder(String validDomainName) throws Exception { LOGGER.debug("valid domain name '{}' start", validDomainName); PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName(validDomainName).build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertEquals("1707", phoneNumber.getNumber()); assertEquals(validDomainName, phoneNumber.getPhoneContext()); assertEquals(("tel:1707;phone-context="+validDomainName), phoneNumber.getValue()); } @Test public void test_extension_subAddress_conflict_for_GlobalPhoneNumberBuilder() throws PhoneNumberParseException { GlobalPhoneNumberBuilder builder = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555"); builder.build(); //should be valid builder at this point builder.extension("1234"); builder.subAddress("example.a.com"); assertThatIllegalArgumentException() .isThrownBy(() -> builder.build()) .withMessageContaining(EXTENSION) .withMessageContaining(SUBADDRESS); } @Test public void test_extension_subAddress_conflict_for_LocalPhoneNumberBuilder() throws PhoneNumberParseException { LocalPhoneNumberBuilder builder = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888"); builder.build(); //should be valid builder at this point builder.extension("1234"); builder.subAddress("example.a.com"); assertThatIllegalArgumentException() .isThrownBy(() -> builder.build()) .withMessageContaining(EXTENSION) .withMessageContaining(SUBADDRESS); } @Test public void test_extension_for_GlobalPhoneNumberBuilder() throws PhoneNumberParseException { PhoneNumber phoneNumber = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .extension("1234") .build(); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertNull(phoneNumber.getPhoneContext(), "PhoneContext should be null"); assertEquals("+1-888-888-5555", phoneNumber.getNumber()); assertEquals("1234", phoneNumber.getExtension()); assertEquals(("tel:+1-888-888-5555;ext=1234"), phoneNumber.getValue()); } @Test public void test_extension_for_LocalPhoneNumberBuilder() throws PhoneNumberParseException { PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .extension("1234") .build(); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertEquals("888-5555", phoneNumber.getNumber()); assertEquals("+1-888", phoneNumber.getPhoneContext()); assertEquals("1234", phoneNumber.getExtension()); assertEquals(("tel:888-5555;ext=1234;phone-context=+1-888"), phoneNumber.getValue()); } @Test public void test_subAddress_for_GlobalPhoneNumberBuilder() throws PhoneNumberParseException { PhoneNumber phoneNumber = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .subAddress("example.a.com") .build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertNull(phoneNumber.getPhoneContext(), "PhoneContext should be null"); assertEquals("+1-888-888-5555", phoneNumber.getNumber()); assertEquals("example.a.com", phoneNumber.getSubAddress()); assertEquals(("tel:+1-888-888-5555;isub=example.a.com"), phoneNumber.getValue()); } @Test public void test_subAddress_for_LocalPhoneNumberBuilder() throws PhoneNumberParseException { PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .subAddress("example.a.com") .build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertEquals("888-5555", phoneNumber.getNumber()); assertEquals("+1-888", phoneNumber.getPhoneContext()); assertEquals("example.a.com", phoneNumber.getSubAddress()); assertEquals(("tel:888-5555;isub=example.a.com;phone-context=+1-888"), phoneNumber.getValue()); } @Test public void test_adding_params_for_GlobalPhoneNumberBuilder() throws PhoneNumberParseException { PhoneNumber phoneNumber = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .extension("1234") .param("example", "gh234") .param("milhouse", "simpson") .build(); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertNull(phoneNumber.getPhoneContext(), "PhoneContext should be null"); assertEquals("+1-888-888-5555", phoneNumber.getNumber()); assertEquals("1234", phoneNumber.getExtension()); assertEquals(("tel:+1-888-888-5555;ext=1234;example=gh234;milhouse=simpson"), phoneNumber.getValue()); } @Test public void test_adding_params_for_LocalPhoneNumberBuilder() throws PhoneNumberParseException { PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .subAddress("example.a.com") .param("example", "gh234") .param("milhouse", "simpson") .build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertEquals("888-5555", phoneNumber.getNumber()); assertEquals("+1-888", phoneNumber.getPhoneContext()); assertEquals("example.a.com", phoneNumber.getSubAddress()); assertEquals(("tel:888-5555;isub=example.a.com;phone-context=+1-888;example=gh234;milhouse=simpson"), phoneNumber.getValue()); } @Test public void test_adding_invalid_param_to_GlobalPhoneNumberBuilder() throws PhoneNumberParseException { try{ new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").param("example_", "gh234").build(); fail(FAILURE_MESSAGE); } catch (PhoneNumberParseException ex) { assertThat(ex).message().contains(FAILED_TO_PARSE).contains("'_'"); } try{ new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").param("example", "gh234^").build(); fail(FAILURE_MESSAGE); } catch (PhoneNumberParseException ex) { assertThat(ex).message().contains(FAILED_TO_PARSE).contains("'^'"); } try{ new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").param(null, "gh234").build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } try{ new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").param("", "gh234").build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } try{ new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").param("a", null).build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } try{ new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").param("a", "").build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } } @Test public void test_adding_invalid_param_to_LocalPhoneNumberBuilder() throws PhoneNumberParseException { try{ new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("814").param("example*", "gh234").build(); fail(FAILURE_MESSAGE); } catch (PhoneNumberParseException ex) { assertThat(ex).message().contains(FAILED_TO_PARSE).contains("'*'"); } try{ new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("814").param("example", "gh234\\").build(); fail(FAILURE_MESSAGE); } catch (PhoneNumberParseException ex) { assertThat(ex).message().contains(FAILED_TO_PARSE).contains("'\\'"); } try{ new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("814").param(null, "gh234").build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } try{ new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("814").param("", "gh234").build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } try{ new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("814").param("a", null).build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } try{ new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("814").param("a", "").build(); fail(FAILURE_MESSAGE); } catch (IllegalArgumentException ex) { assertThat(ex).message().contains(PARAMS_NAME_VALUE); } } @Test public void test_valid_subAddress() throws PhoneNumberParseException { PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName("example.a.com") .subAddress("%20azAZ09?@=,+$&/:_!~.-()") .build(); assertNull(phoneNumber.getExtension(), "Extension should be null"); assertEquals("1707", phoneNumber.getNumber()); assertEquals("example.a.com", phoneNumber.getPhoneContext()); assertEquals("%20azAZ09?@=,+$&/:_!~.-()", phoneNumber.getSubAddress()); assertEquals(("tel:1707;isub=%20azAZ09?@=,+$&/:_!~.-();phone-context=example.a.com"), phoneNumber.getValue()); } @Test public void test_invalid_subAddress() { assertThatExceptionOfType(PhoneNumberParseException.class) .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1707").domainName("example.a.com").subAddress("azAZ09^example.(com)").build()) .withMessageContaining(FAILED_TO_PARSE); } @SuppressWarnings("unused") private static String[] getInvalidExtensions() { return new String[] { "", "A", "b", "#1234", "*1234", "@1234", "23 1234", "123 1234", "1234 1234", "123 12345", "123 123 456", "+1-888-888-8888" }; } @SuppressWarnings("unused") private static String[] getValidExtensions() { return new String[] { "1", "1234", "12345", "123-1234", "123.1234", "(123)-1234", "(123).1234", "23-1234", "(23)-1234", "(23).1234", "1234-1234", "1234.1234", "(1234)-1234", "(1234).1234", "123-123456", "123.123456", "(123)-123456", "(123).123456", "(123)-123-456", "(123).123.456", "(22).33.44.55", }; } @ParameterizedTest @MethodSource("getValidExtensions") public void test_valid_extension(String validExtension) throws PhoneNumberParseException { LOGGER.debug("valid extension '{}' start", validExtension); PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("1234-5678").countryCode("+44").areaCode("20") .extension(validExtension) .build(); assertEquals(validExtension, phoneNumber.getExtension()); assertNull(phoneNumber.getSubAddress(), "SubAddress should be null"); assertEquals("1234-5678", phoneNumber.getNumber()); assertEquals("+44-20", phoneNumber.getPhoneContext()); assertEquals(("tel:1234-5678;ext=" + validExtension + ";phone-context=+44-20"), phoneNumber.getValue()); } @ParameterizedTest @MethodSource("getInvalidExtensions") public void test_invalid_extension(String invalidExtension) throws PhoneNumberParseException { LOGGER.debug("invalid extension {}", invalidExtension); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1234-5678").countryCode("+44").areaCode("20").extension(invalidExtension).build()) .withMessageContaining(EXTENSION); String temp = invalidExtension != null ? (" " + invalidExtension + " ") : null; LOGGER.debug("invalid extension '{}' start", temp); assertThatIllegalArgumentException() .isThrownBy(() -> new LocalPhoneNumberBuilder().subscriberNumber("1234-5678").countryCode("+44").areaCode("20").extension(invalidExtension).build()) .withMessageContaining(EXTENSION); } @Test public void test_paramsToLowerCase() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .param("ABCDE", "FGHIJKLM") .param("NOPQR", "STUVWXYZ.-_") .build(); Map<String, String> lowerP = ph.paramsToLowerCase(); assertEquals(2, lowerP.size()); assertEquals("fghijklm", lowerP.get("abcde")); assertEquals("stuvwxyz.-_", lowerP.get("nopqr")); } @Test public void test_equalsIgnoreCaseAndOrderParams_not_equal() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .param("A", "B") .param("C", "D_") .build(); PhoneNumber phOther = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .param("A", "B") .param("C", "E_") .build(); assertFalse(ph.equalsIgnoreCaseAndOrderParams(phOther.getParams())); } @Test public void test_equalsIgnoreCaseAndOrderParams_equal() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .param("A", "B") .param("C", "D_") .build(); PhoneNumber phOther = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .param("c", "D_") .param("A", "b") .build(); assert(ph.equalsIgnoreCaseAndOrderParams(phOther.getParams())); } @Test public void test_equalsAndHashCode_globalNumber() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").build(); assert(ph.isGlobalNumber()); PhoneNumber phSame = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").build(); assert(phSame.isGlobalNumber()); PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); assertFalse(localPh.isGlobalNumber()); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); assertFalse(localPhSame.isGlobalNumber()); assertEquals(ph, phSame); assertEquals(localPh, localPhSame); assertNotEquals(ph, localPh); } @Test public void test_equalsAndHashCode_number() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555").build(); PhoneNumber phSame = new GlobalPhoneNumberBuilder().globalNumber("+18888885555").build(); PhoneNumber phDiff = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5556").build(); assertEquals(ph, phSame); assertEquals(ph.hashCode(), phSame.hashCode()); assertNotEquals(ph, phDiff); assertNotEquals(ph.hashCode(), phDiff.hashCode()); PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("8885555").countryCode("+1").areaCode("888").build(); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-6666").countryCode("+1").areaCode("888").build(); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); } @Test public void test_equalsAndHashCode_extension() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .extension("12(34)") .build(); PhoneNumber phSame = new GlobalPhoneNumberBuilder().globalNumber("+18888885555") .extension("1234") .build(); PhoneNumber phDiff = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .extension("1235") .build(); assertEquals(ph, phSame); assertEquals(ph.hashCode(), phSame.hashCode()); assertNotEquals(ph, phDiff); assertNotEquals(ph.hashCode(), phDiff.hashCode()); PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .extension("12(34)") .build(); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("8885555").countryCode("+1").areaCode("888") .extension("1234") .build(); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .extension("1235") .build(); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); } @Test public void test_equalsAndHashCode_subAddress() throws PhoneNumberParseException { PhoneNumber ph = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .subAddress("example.ZXC.com") .build(); PhoneNumber phSame = new GlobalPhoneNumberBuilder().globalNumber("+18888885555") .subAddress("Example.zxc.com") .build(); PhoneNumber phDiff = new GlobalPhoneNumberBuilder().globalNumber("+1-888-888-5555") .subAddress("example.zxc.gov") .build(); assertEquals(ph, phSame); assertEquals(ph.hashCode(), phSame.hashCode()); assertNotEquals(ph, phDiff); assertNotEquals(ph.hashCode(), phDiff.hashCode()); PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .subAddress("example.ZXC.com") .build(); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("8885555").countryCode("+1").areaCode("888") .subAddress("Example.zxc.com") .build(); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .subAddress("example.zxc.gov") .build(); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); } @Test public void test_equalsAndHashCode_phoneContext_as_domainName() throws PhoneNumberParseException { PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").domainName("example.ZXC.com").build(); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("8885555").domainName("Example.zxc.com").build(); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").domainName("example.zxc.gov").build(); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); } @Test public void test_equalsAndHashCode_phoneContext_as_digits() throws PhoneNumberParseException { PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("886").build(); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); } @Test public void test_equalsAndHashCode_params() throws PhoneNumberParseException { PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .param("A","c") .param("B","d") .build(); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .param("a","C") .param("b","D") .build(); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888") .param("A","e") .param("B","d") .build(); PhoneNumber nullParamsPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); assertNotEquals(localPh, nullParamsPh); assertNotEquals(localPh.hashCode(), nullParamsPh.hashCode()); PhoneNumber globalPh = new GlobalPhoneNumberBuilder().globalNumber("+683-5791") .param("A","c") .param("B","d") .build(); PhoneNumber globalPhSame = new GlobalPhoneNumberBuilder().globalNumber("+683-5791") .param("a","C") .param("b","D") .build(); PhoneNumber globalPhDiff = new GlobalPhoneNumberBuilder().globalNumber("+683-5791") .param("A","e") .param("f","D") .build(); PhoneNumber nullParamsGlobalPh = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); assertEquals(globalPh, globalPhSame); assertEquals(globalPh.hashCode(), globalPhSame.hashCode()); assertNotEquals(globalPh, globalPhDiff); assertNotEquals(globalPh.hashCode(), globalPhDiff.hashCode()); assertNotEquals(globalPh, nullParamsGlobalPh); assertNotEquals(globalPh.hashCode(), nullParamsGlobalPh.hashCode()); } @Test public void test_equalsAndHashCode_phoneContext_primary_flag() throws PhoneNumberParseException { PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); localPh.setPrimary(Boolean.TRUE); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); localPhSame.setPrimary(Boolean.TRUE); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); localPhDiff.setPrimary(Boolean.FALSE); PhoneNumber nullPrimaryPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); nullPrimaryPh.setPrimary(null); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); assertNotEquals(localPh, nullPrimaryPh); assertNotEquals(localPh.hashCode(), nullPrimaryPh.hashCode()); PhoneNumber globalPh = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); globalPh.setPrimary(true); PhoneNumber globalPhSame = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); globalPhSame.setPrimary(true); PhoneNumber globalPhDiff = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); globalPhDiff.setPrimary(false); PhoneNumber nullPrimaryGlobalPh = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); nullPrimaryGlobalPh.setPrimary(null); assertEquals(globalPh, globalPhSame); assertEquals(globalPh.hashCode(), globalPhSame.hashCode()); assertNotEquals(globalPh, globalPhDiff); assertNotEquals(globalPh.hashCode(), globalPhDiff.hashCode()); assertNotEquals(globalPh, nullPrimaryGlobalPh); assertNotEquals(globalPh.hashCode(), nullPrimaryGlobalPh.hashCode()); } @Test public void test_equalsAndHashCode_phoneContext_type() throws PhoneNumberParseException { PhoneNumber localPh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); localPh.setType("work"); PhoneNumber localPhSame = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); localPhSame.setType("WORK"); PhoneNumber localPhDiff = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); localPhDiff.setType("HOME"); PhoneNumber nullTypePh = new LocalPhoneNumberBuilder().subscriberNumber("888-5555").countryCode("+1").areaCode("888").build(); assertNull(nullTypePh.getType()); assertEquals(localPh, localPhSame); assertEquals(localPh.hashCode(), localPhSame.hashCode()); assertNotEquals(localPh, localPhDiff); assertNotEquals(localPh.hashCode(), localPhDiff.hashCode()); assertNotEquals(localPh, nullTypePh); assertNotEquals(localPh.hashCode(), nullTypePh.hashCode()); PhoneNumber globalPh = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); globalPh.setType("mobile"); PhoneNumber globalPhSame = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); globalPhSame.setType("MOBILE"); PhoneNumber globalPhDiff = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); globalPhDiff.setType("fax"); PhoneNumber nullTypeGlobalPh = new GlobalPhoneNumberBuilder().globalNumber("+683-5791").build(); assertNull(nullTypeGlobalPh.getType()); assertEquals(globalPh, globalPhSame); assertEquals(globalPh.hashCode(), globalPhSame.hashCode()); assertNotEquals(globalPh, globalPhDiff); assertNotEquals(globalPh.hashCode(), globalPhDiff.hashCode()); assertNotEquals(globalPh, nullTypeGlobalPh); assertNotEquals(globalPh.hashCode(), nullTypeGlobalPh.hashCode()); } }
4,168
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/resources/PhoneNumberJsonTest.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.directory.scim.spec.ObjectMapperFactory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class PhoneNumberJsonTest { @Test public void testPhoneNumberJson() throws Exception { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setValue("tel:+12083869507"); ObjectMapper objectMapper = getObjectMapper(); String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(phoneNumber); PhoneNumber readValue = objectMapper.readValue(json, PhoneNumber.class); assertEquals(phoneNumber.getNumber(), readValue.getNumber()); assertEquals(phoneNumber.getExtension(), readValue.getExtension()); assertEquals(phoneNumber.isDomainPhoneContext(), readValue.isDomainPhoneContext()); assertEquals(phoneNumber.isGlobalNumber(), readValue.isGlobalNumber()); assertEquals(phoneNumber.getPhoneContext(), readValue.getPhoneContext()); assertEquals(phoneNumber.getSubAddress(), readValue.getSubAddress()); assertEquals(phoneNumber.getPrimary(), readValue.getPrimary()); assertEquals(phoneNumber.getDisplay(), readValue.getDisplay()); assertEquals(phoneNumber.getType(), readValue.getType()); assertEquals(phoneNumber.getValue(), readValue.getValue()); } private ObjectMapper getObjectMapper() { ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(Include.NON_NULL); return objectMapper; } }
4,169
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/phonenumber/PhoneNumberTest.java
/* * 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. */ package org.apache.directory.scim.spec.phonenumber; import org.apache.directory.scim.spec.resources.PhoneNumber; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.assertj.core.api.Assertions.assertThat; public class PhoneNumberTest { @SuppressWarnings("unused") private static String[] getAllValidPhones() { return new String[] { "tel:7042;phone-context=example.com",//local number "tel:863-1234;phone-context=+1-914-555",//local number "tel:235-1707;ext=4567;phone-context=+1-814-555",//local with ext and context "tel:235-1707;isub=example.sub.com;phone-context=+1-814-555",//local with isub and context "tel:235-1707;ext=4567;phone-context=+1-814-555;par2=ghnkl23",//local with ext, context and additional param "tel:235-1707;isub=example.sub.com;phone-context=+1-814-555;par2=ghnkl23",//local with isub, context and additional param "tel:+44-20-1234-5678",//global with visualSeparator - "tel:+44.20.1234.5678",//global with visualSeparator . "tel:+44.20.1234.5678;ext=4567",//global with ext "tel:+44.20.1234.5678;isub=example.sub.com",//global with isub "tel:+44.20.1234.5678;ext=4567;par2=ghnkl23",//global with ext and additional param "tel:+44.20.1234.5678;isub=example.sub.com;par2=ghnkl23",//global with isub and additional param "tel:+1-201-555-0123",//US global format with visualSeparator - "tel:+1.201.555.0123",//US global format with visualSeparator . "tel:+1(201)555.0123",//US global format with visualSeparator . and () "tel:+1(201)555-0123",//US global format with visualSeparator - and () "tel:+1-201-555-0123;ext=1234",//US global format with extension "tel:+880-23-6666-7410",//Bangladesh "tel:+886-912-345678",//Taiwan mobile "tel:+674-556-7815",//Nauru, Oman "tel:+676-27-987",//Tonga "tel:+683-5791",//Niue & Tokelau "tel:+686-22910",//Kiribati "tel:+32-2-555-12-12", //Belguim big city "tel:+32-71-123-456", //Belguim small city "tel:+32-478-12-34-56", //Belguim mobile "tel:+30-21-2-228-4931", //Greece "tel:+352-79-0000", //Luxemburg "tel:+352-2679-0000", "tel:+352-4-000-00", "tel:+970-08-240-7851",//Palestine "tel:+970-059-240-7851",//Palestine mobile "tel:+998-7071-123456789",//Uzbekistan "tel:+998-7071-12345678", "tel:+998-7071-1234567", "tel:+998-74-123456789", "tel:+998-751-12345678", "tel:+998-62-1234567", "tel:+996-312-123456",//Kyrgyzstan "tel:+359-2-912-4501",//Bulgaria "tel:+359-37-9873-571",//Bulgaria mobile "tel:+358-9-333-444",//Finland "tel:+358-045-123-45", //Finland mobile "tel:+358-050-123-45-6", //Finland mobile "tel:+358-045-123-45-67", //Finland mobile "tel:+357-22-123456",//Cyprus "tel:+357-9-987456",//Cyprus mobile "tel:+44-28-9034-0812", //Northern Ireland "tel:+44-7333-187-891", //Nothern Ireland mobile "tel:+351-12-241-6789", //Portugal "tel:+351-90-288-6789", //Portugal mobile "tel:+506-5710-9874", //Costa Rica "tel:+66-2-2134567", //Thailand "tel:+66-44-2134567", //Thailand "tel:+66-080-6345678", //Thailand mobile "tel:+673-215-9642", //Brunei "tel:+386-1-019-45-12",//Slovenia "tel:+386-1-030-99-35",//Slovenia mobile "tel:+7-499-123-78-56", //Russia "tel:+52-744-235-4410",//Mexico "tel:+52-55-235-4410",//Mexico "tel:+855-23-430715", //Cambodia "tel:+855-23-4307159", //Cambodia "tel:+855-76-234-5678", //Cambodia mobile "tel:+86-123-4567-8901", //China mobile "tel:+86-852-123-4567", //China landline "tel:+86-85-1234-5678", //China landline "tel:+852-145-6789-0123", //China mobile "tel:+852-852-123-4567", //China landline "tel:+852-85-1234-5678", //China landline "tel:+886-198-6541-2579", //China mobile "tel:+886-852-123-4567", //China landline "tel:+886-85-1234-5678", //China landline "tel:+977-10-512-345", //Napal "tel:+373-24-91-13-20", //Moldova "tel:+33-03-71-13-20-43", //France "tel:+43-(08)-9345-6765",//Austrailia +43 "tel:+49(05236)-5217775",//Germany +49 "tel:+49(032998)-651224", "tel:+49(065)-51140357", "tel:+81-004-477-3632",//Japan "tel:+81-044-021-3258", "tel:+81-005-920-5122", "tel:+44-(026)-6987-1101",//UK "tel:+44-055-6956-7230", "tel:+44-(0117)-204-2623", "tel:+44-07624-958791", "tel:+1-(495)-172-7974",//Canada "tel:+1-376-597-9524" }; } @SuppressWarnings("unused") private static String[] getAllInvalidPhones() { return new String[] { "",//missing prefix and numbers "tel:",//missing numbers "201-555-0123",//missing prefix "tel:201 555 0123",//not allowed spaces "tel:201-555-0123",//no phone-context "tel:814-235-1707;ext=4567", //no phone-context for local "tel:235-1707;ext=4567;ext=1234;phone-context:+1=814-555", //two ext params "tel:235-1707;phone-context:+1=814-555;ext=4567", //ext in wrong order "tel:235-1707;ext=4567;isub=example.phone.com;phone-context:+1=814-555",//has both ext and isub; allowed only one "tel:1707;isub=sub.example.com",//no phone-context "tel:1707;ext=1234;isub=sub.example.com",//local with ext and isub, no phone-context "tel:865-8773;ext=#44;phone-context:+1-814-555",//local with symbol in ext param "tel:(814) 235-1707;ext=4567",//spaces not allowed "+1-201-555-0123", //no prefix "tel:+1-814-235-1707;ext=4567;ext=1234", //two ext params "tel:+1-814-235-1707;ext=4567;isub=example.phone.com", //has both ext and isub; allowed only one "+44.20.1234.5678",//no prefix "tel:+44-20-1234-5678;phone-context=+44",//phone-context not allowed on global number "tel:+44-20-1234-5678;ext=#44", //global with symbol in ext param "tel:+358-4x-123-4", //Finland mobile (wikipedia says that this is ok???) }; } @ParameterizedTest @MethodSource("getAllValidPhones") public void test_parser_with_valid_phone_numbers(String phoneUri) throws Exception { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setValue(phoneUri, true); assertThat(phoneNumber.getValue()).isEqualTo(phoneUri); } @ParameterizedTest @MethodSource("getAllInvalidPhones") public void test_parser_with_invalid_phone_numbers(String phoneUri) throws PhoneNumberParseException { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setValue(phoneUri); // non-strict parsing should work assertThat(phoneNumber.getValue()).isEqualTo(phoneUri); // strict parsing should fail Assertions.assertThrows(PhoneNumberParseException.class, () -> new PhoneNumber().setValue(phoneUri, true)); } }
4,170
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/schema/SchemaTest.java
/* * 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. */ package org.apache.directory.scim.spec.schema; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.directory.scim.spec.ObjectMapperFactory; import org.apache.directory.scim.spec.schema.Schema.Attribute; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import jakarta.validation.ConstraintViolation; import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; import java.io.InputStream; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class SchemaTest { static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); Validator validator; @BeforeEach public void setUp() { validator = validatorFactory.getValidator(); } /** * Tests that the schemas published in the SCIM schema specification are valid * when unmarshalled into the equivalent classes developed from those * specifications. * * @param schemaFileName * the name of the resource on the classpath that contains the JSON * representation of the schema. */ @ParameterizedTest @ValueSource( strings = { "schemas/urn:ietf:params:scim:schemas:core:2.0:User.json", "schemas/urn:ietf:params:scim:schemas:core:2.0:Group.json", "schemas/urn:ietf:params:scim:schemas:core:2.0:ResourceType.json", "schemas/urn:ietf:params:scim:schemas:core:2.0:Schema.json", "schemas/urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig.json", "schemas/urn:ietf:params:scim:schemas:extension:enterprise:2.0:User.json" }) public void testUnmarshallingProvidedSchemas(String schemaFileName) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(schemaFileName); ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); // Unmarshall the JSON document to a Schema and its associated object graph. Schema schema = null; try { schema = objectMapper.readValue(inputStream, Schema.class); assertNotNull(schema); } catch (Throwable t) { fail("Unexpected Throwable was caught while unmarshalling JSON: " + t.getLocalizedMessage()); } // Validate the unmarshalled object graph to confirm the JSON // representations meet the schema specification. if (schema != null) { Set<ConstraintViolation<Schema>> schemaViolations = validator.validate(schema); assertTrue(schemaViolations.isEmpty()); for (Attribute attribute : schema.getAttributes()) { Set<ConstraintViolation<Attribute>> attributeViolations = validator.validate(attribute); assertTrue(attributeViolations.isEmpty()); } Meta meta = schema.getMeta(); if (meta != null) { Set<ConstraintViolation<Meta>> metaViolations = validator.validate(meta); assertTrue(metaViolations.isEmpty()); } } } @Test @Disabled public void testGetId() { fail("Not yet implemented"); } @Test @Disabled public void testSetId() { fail("Not yet implemented"); } @Test @Disabled public void testGetName() { fail("Not yet implemented"); } @Test @Disabled public void testSetName() { fail("Not yet implemented"); } @Test @Disabled public void testGetDescription() { fail("Not yet implemented"); } @Test @Disabled public void testSetDescription() { fail("Not yet implemented"); } @Test @Disabled public void testGetAttributes() { fail("Not yet implemented"); } @Test @Disabled public void testSetAttributes() { fail("Not yet implemented"); } }
4,171
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/schema/MapperTest.java
/* * 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. */ package org.apache.directory.scim.spec.schema; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.text.ParseException; import java.time.Instant; import java.util.*; import static org.junit.jupiter.api.Assertions.assertEquals; public class MapperTest { static final String[] ISO_DATETIME_EXAMPLES = { "2015-04-26T01:37:17+00:00", "2015-04-26T01:37:17Z" }; static String[] getIsoDateTimeExamples() { return ISO_DATETIME_EXAMPLES; } @ParameterizedTest @MethodSource("getIsoDateTimeExamples") public void testConvertDateTimeFromString(String isoDateTime) throws ParseException { Mapper mapper = new Mapper(); Instant instant = mapper.convertDateTime(isoDateTime); TimeZone timeZone = new SimpleTimeZone(0, "GMT"); GregorianCalendar calendar = new GregorianCalendar(timeZone); calendar.setTime(Date.from(instant)); assertEquals(2015, calendar.get(Calendar.YEAR)); assertEquals(3, calendar.get(Calendar.MONTH)); assertEquals(26, calendar.get(Calendar.DATE)); assertEquals(1, calendar.get(Calendar.HOUR_OF_DAY)); assertEquals(37, calendar.get(Calendar.MINUTE)); assertEquals(17, calendar.get(Calendar.SECOND)); } @Test @Disabled public void convertDateTimeFromDate() { Mapper mapper = new Mapper(); TimeZone timeZone = new SimpleTimeZone(0, "GMT"); GregorianCalendar calendar = new GregorianCalendar(timeZone); calendar.set(Calendar.YEAR, 2015); calendar.set(Calendar.MONTH, 03); calendar.set(Calendar.DATE, 26); calendar.set(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 37); calendar.set(Calendar.SECOND, 17); Instant instant = calendar.toInstant(); String actualDateTime = mapper.convertDateTime(instant); assertEquals(ISO_DATETIME_EXAMPLES[0], actualDateTime); } }
4,172
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/patch/PatchOperationPathTest.java
/* * 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. */ package org.apache.directory.scim.spec.patch; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import lombok.extern.slf4j.Slf4j; @Slf4j public class PatchOperationPathTest { public static String[] pathValues() { return new String[] { "members", "name.familyName", "addresses[type eq \"work\"]", "members[value eq \"2819c223-7f76-453a-919d-413861904646\"]", "members[value eq \"2819c223-7f76-453a-919d-413861904646\"].displayName" }; } @ParameterizedTest @MethodSource("pathValues") public void testPathParsing(String value) throws Exception { PatchOperationPath path = new PatchOperationPath(value); log.debug("ValuePathExpression: {}", path.getValuePathExpression()); String result = path.toString(); log.debug(result); Assertions.assertNotNull(path.getValuePathExpression()); Assertions.assertEquals(value.toLowerCase(), result.toLowerCase()); } }
4,173
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderStringTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class FilterBuilderStringTest { @Test public void testEndsWith() throws FilterParseException { Filter filter = FilterBuilder.create().endsWith("address.streetAddress", "Way").build(); Filter expected = new Filter("address.streetAddress EW \"Way\""); assertThat(filter).isEqualTo(expected); } @Test public void testStartsWith() throws FilterParseException { Filter filter = FilterBuilder.create().startsWith("address.streetAddress", "133").build(); Filter expected = new Filter("address.streetAddress SW \"133\""); assertThat(filter).isEqualTo(expected); } @Test public void testContains() throws FilterParseException { Filter filter = FilterBuilder.create().contains("address.streetAddress", "MacDuff").build(); Filter expected = new Filter("address.streetAddress CO \"MacDuff\""); assertThat(filter).isEqualTo(expected); } }
4,174
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FilterTest extends AbstractLexerParserTest { private static final Logger LOG = LoggerFactory.getLogger(FilterTest.class); @SuppressWarnings("unused") private static String[] getAllFilters() { return ALL; } @ParameterizedTest @MethodSource("getAllFilters") public void test(String filterText) throws Exception { LOG.debug("Running Filter Parser test on input: {}", filterText); Filter filter = new Filter(filterText); FilterExpression expression = filter.getExpression(); LOG.debug("Parsed String: {}", expression.toFilter()); Assertions.assertNotNull(expression); } }
4,175
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderLessThanTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class FilterBuilderLessThanTest { static final Integer[] INT_EXAMPLES = { 1, 12, 123, 1234, 12345, 123456 }; static final Long[] LONG_EXAMPLES = { 3L, 33L, 333L, 3333L, 33333L, 333333L }; static final Float [] FLOAT_EXAMPLES = {.14f, 3.14f, 2.1415f, 3.14E+10f, 333.14f}; static final Double [] DOUBLE_EXAMPLES = {.14, 3.14, 2.1415, 3.14E+10, 333.14}; static Integer[] getIntExamples() { return INT_EXAMPLES; } static Long[] getLongExamples() { return LONG_EXAMPLES; } static Float[] getFloatExamples() { return FLOAT_EXAMPLES; } static Double[] getDoubleExamples() { return DOUBLE_EXAMPLES; } @ParameterizedTest @MethodSource("getIntExamples") public void testLessThanT_Int(Integer arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LT " + arg); assertThat(filter).isEqualTo(expected); } @ParameterizedTest @MethodSource("getLongExamples") public void testLessThanT_Long(Long arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LT " + arg); // values are parsed to integers, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getFloatExamples") public void testLessThanT_Float(Float arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LT " + arg); // values are parsed to doubles, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getDoubleExamples") public void testLessThanT_Double(Double arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LT " + arg); assertThat(filter).isEqualTo(expected); } @Test public void testLessThanDate() throws FilterParseException { Date now = new Date(); Filter filter = FilterBuilder.create().lessThan("dog.dob", now).build(); Filter expected = new Filter("dog.dob LT \"" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").format(now) + "\""); // FIXME: format is missing TZ // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testLessThanLocalDate() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().lessThan("dog.dob", now).build(); Filter expected = new Filter("dog.dob LT \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testLessThanLocalDateTime() throws FilterParseException { LocalDateTime now = LocalDateTime.now(); Filter filter = FilterBuilder.create().lessThan("dog.dob", now).build(); Filter expected = new Filter("dog.dob LT \"" + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getIntExamples") public void testLessThanOrEqualsT_Int(Integer arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LE " + arg); assertThat(filter).isEqualTo(expected); } @ParameterizedTest @MethodSource("getLongExamples") public void testLessThanOrEqualsT_Long(Long arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LE " + arg); // values are parsed to doubles, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getFloatExamples") public void testLessThanOrEqualsT_Float(Float arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LE " + arg); // values are parsed to doubles, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getDoubleExamples") public void testLessThanOrEqualsT_Double(Double arg) throws FilterParseException { Filter filter = FilterBuilder.create().lessThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight LE " + arg); // values are parsed to doubles, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testLessThanOrEqualsDate() throws FilterParseException { Date now = new Date(); Filter filter = FilterBuilder.create().lessThanOrEquals("dog.dob", now).build(); Filter expected = new Filter("dog.dob LE \"" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").format(now) + "\""); // FIXME: format is missing TZ // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testLessThanOrEqualsLocalDate() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().lessThanOrEquals("dog.dob", now).build(); Filter expected = new Filter("dog.dob LE \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testLessThanOrEqualsLocalDateTime() throws FilterParseException { LocalDateTime now = LocalDateTime.now(); Filter filter = FilterBuilder.create().lessThanOrEquals("dog.dob", now).build(); Filter expected = new Filter("dog.dob LE \"" + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } }
4,176
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderPresentTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class FilterBuilderPresentTest { @Test public void testAttributePresent() throws FilterParseException { Filter filter = FilterBuilder.create().present("address.streetAddress").build(); Filter expected = new Filter("address.streetAddress PR"); assertThat(filter).isEqualTo(expected); } @Test public void testStartsWith() throws FilterParseException { Filter filter = FilterBuilder.create() .present("address.streetAddress") .and(f -> f.equalTo("address.region", "CA")) .build(); Filter expected = new Filter("address.streetAddress PR AND address.region EQ \"CA\""); assertThat(filter).isEqualTo(expected); } }
4,177
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/AbstractLexerParserTest.java
/* * 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. */ /** * */ package org.apache.directory.scim.spec.filter; import org.apache.commons.lang3.ArrayUtils; /** * @author stevemoyer * */ public abstract class AbstractLexerParserTest { protected static final String NO_FILTER = ""; protected static final String JOHN_FILTER_MIXED_CASE_1 = "userName Eq \"john\""; protected static final String JOHN_FILTER_MIXED_CASE_2 = "Username eq \"john\""; protected static final String JOHN_FILTER_MIXED_CASE_3 = "Username EQ \"john\""; protected static final String JOHN_FILTER_MIXED_CASE_4 = "USERNAME EQ \"john\""; protected static final String EXAMPLE_1 = "userName eq \"bjensen\""; protected static final String EXAMPLE_2 = "name.familyName co \"O'Malley\""; protected static final String EXAMPLE_3 = "userName sw \"J\""; protected static final String EXAMPLE_4 = "title pr"; protected static final String EXAMPLE_5 = "meta.lastModified gt \"2011-05-13T04:42:34Z\""; protected static final String EXAMPLE_6 = "meta.lastModified ge \"2011-05-13T04:42:34Z\""; protected static final String EXAMPLE_7 = "meta.lastModified lt \"2011-05-13T04:42:34Z\""; protected static final String EXAMPLE_8 = "meta.lastModified le \"2011-05-13T04:42:34Z\""; protected static final String EXAMPLE_9 = "title pr and userType eq \"Employee\""; protected static final String EXAMPLE_10 = "title pr or userType eq \"Intern\""; protected static final String EXAMPLE_11 = "userType eq \"Employee\" and (emails co \"example.com\" or emails co \"example.org\")"; protected static final String[] EXAMPLES = { EXAMPLE_1, EXAMPLE_2, EXAMPLE_3, EXAMPLE_4, EXAMPLE_5, EXAMPLE_6, EXAMPLE_7, EXAMPLE_8, EXAMPLE_9, EXAMPLE_10, EXAMPLE_11 }; protected static final String EXTRA_1 = "(emails co \"example.com\" or emails co \"example.org\")"; protected static final String EXTRA_2 = "(emails co \"example.com\" or emails co \"example.org\") and userType eq \"Employee\""; protected static final String[] EXTRAS = { EXTRA_1, EXTRA_2 }; protected static final String GROUP_EXAMPLE_1 = "not(userType eq \"Employee\")"; protected static final String GROUP_EXAMPLE_1_1 = "(userType eq \"Employee\")"; protected static final String GROUP_EXAMPLE_1_2 = "NOT(userType eq \"Employee\")"; protected static final String GROUP_EXAMPLE_1_3 = "NOT (userType eq \"Employee\")"; protected static final String GROUP_EXAMPLE_2 = "userType eq \"Employee\" and not(emails co \"example.com\" or emails co \"example.org\")"; protected static final String GROUP_EXAMPLE_2_1 = "userType eq \"Employee\" and (emails co \"example.com\" or emails co \"example.org\")"; protected static final String GROUP_EXAMPLE_2_2 = "userType eq \"Employee\" and NOT(emails co \"example.com\" or emails co \"example.org\")"; protected static final String GROUP_EXAMPLE_2_3 = "userType eq \"Employee\" and NOT (emails co \"example.com\" or emails co \"example.org\")"; protected static final String GROUP_EXAMPLE_3 = "not(userType eq \"Employee\") and not(userType eq \"Intern\")"; protected static final String GROUP_EXAMPLE_3_1 = "(userType eq \"Employee\") and (userType eq \"Intern\")"; protected static final String GROUP_EXAMPLE_4 = "not(userType eq \"Employee\" or userType eq \"Intern\")"; protected static final String GROUP_EXAMPLE_4_1 = "(userType eq \"Employee\" or userType eq \"Intern\")"; protected static final String[] GROUPS = { GROUP_EXAMPLE_1, GROUP_EXAMPLE_1_1, GROUP_EXAMPLE_1_2, GROUP_EXAMPLE_1_3, GROUP_EXAMPLE_2, GROUP_EXAMPLE_2_1, GROUP_EXAMPLE_2_2, GROUP_EXAMPLE_2_3, GROUP_EXAMPLE_3, GROUP_EXAMPLE_3_1, GROUP_EXAMPLE_4, GROUP_EXAMPLE_4_1 }; protected static final String VALUE_EXPRESSION_1 = "emails[type eq \"work\"]"; protected static final String VALUE_EXPRESSION_2 = "emails[type eq \"work\" and value co \"@example.com\"]"; protected static final String VALUE_EXPRESSION_2_1 = "emails[type eq \"work\" AND value co \"@example.com\"]"; protected static final String VALUE_EXPRESSION_3 = "emails[type eq \"work\" and value co \"@example.com\"] or ims[type eq \"xmpp\" and value co \"@foo.com\"]"; protected static final String VALUE_EXPRESSION_3_1 = "emails[type eq \"work\" AND value co \"@example.com\"] OR ims[type eq \"xmpp\" and value co \"@foo.com\"]"; protected static final String[] VALUE_EXPRESSIONS = { VALUE_EXPRESSION_1, VALUE_EXPRESSION_2, VALUE_EXPRESSION_2_1, VALUE_EXPRESSION_3, VALUE_EXPRESSION_3_1}; protected static final String EXTENSION_1 = "urn:example:params:scim:schemas:extension:ExampleExtension:example pr"; protected static final String EXTENSION_2 = "urn:example:params:scim:schemas:extension:ExampleExtension:example.sub pr"; protected static final String EXTENSION_3 = "urn:example:params:scim:schemas:extension:ExampleExtension:examples[value eq true or type sw \"example\"]"; protected static final String EXTENSION_4 = "urn:example:params:scim:schemas:extension:ExampleExtension:example1 eq \"example1\" and urn:example:params:scim:schemas:extension:ExampleExtension:example2 eq \"example2\""; protected static final String[] EXTENSIONS = { EXTENSION_1, EXTENSION_2, EXTENSION_3, EXTENSION_4 }; protected static final String[] EXAMPLES_AND_EXTRAS = ArrayUtils.addAll(EXAMPLES, EXTRAS); protected static final String[] GROUPS_AND_VALUE_EXPRESSIONS = ArrayUtils.addAll(GROUPS, VALUE_EXPRESSIONS); protected static final String[] ALL = ArrayUtils.addAll(ArrayUtils.addAll(EXAMPLES_AND_EXTRAS, GROUPS_AND_VALUE_EXPRESSIONS), EXTENSIONS); protected static final String[] MIXED_CASE = { JOHN_FILTER_MIXED_CASE_1, JOHN_FILTER_MIXED_CASE_2, JOHN_FILTER_MIXED_CASE_3, JOHN_FILTER_MIXED_CASE_4 }; protected static final String[] INPUT_ATTRIBUTE_VALUES_WITH_SPACES_NEWLINES_AND_CARRIAGE_RETURNS = { "streetAddress EQ \"111 Heritage Way\"", "streetAddress EQ \"111 Heritage Way\nSuite S\"", "streetAddress EQ \"111 Heritage Way\rSuite S\"" }; protected static final String[][] EXPECTED_ATTRIBUTE_VALUES_WITH_SPACES_NEWLINES_AND_CARRIAGE_RETURNS = { { "streetAddress", "EQ", "\"111 Heritage Way\"" }, { "streetAddress", "EQ", "\"111 Heritage Way\nSuite S\"" }, { "streetAddress", "EQ", "\"111 Heritage Way\rSuite S\"" } }; }
4,178
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderGreaterTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class FilterBuilderGreaterTest { static final Integer[] INT_EXAMPLES = { -1, -10, -111, 1, 12, 123, 1234, 12345, 123456 }; static final Long[] LONG_EXAMPLES = { -1L, -10L, -111L, 3L, 33L, 333L, 3333L, 33333L, 333333L }; static final Float [] FLOAT_EXAMPLES = {.14f, 3.14f, 2.1415f, 3.14E+10f, 333.14f}; static final Double [] DOUBLE_EXAMPLES = {.14, 3.14, 2.1415, 3.14E+10, 333.14}; static Integer[] getIntExamples() { return INT_EXAMPLES; } static Long[] getLongExamples() { return LONG_EXAMPLES; } static Float[] getFloatExamples() { return FLOAT_EXAMPLES; } static Double[] getDoubleExamples() { return DOUBLE_EXAMPLES; } @ParameterizedTest @MethodSource("getIntExamples") public void testGreaterThanT_Int(Integer arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GT " + arg); assertThat(filter).isEqualTo(expected); } @ParameterizedTest @MethodSource("getLongExamples") public void testGreaterThan_Long(Long arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GT " + arg); // values are parsed to integers, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getFloatExamples") public void testGreaterThanT_Float(Float arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GT " + arg); // values are parsed to doubles, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getDoubleExamples") public void testGreaterThanT_Double(Double arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThan("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GT " + arg); assertThat(filter).isEqualTo(expected); } @Test public void testGreaterThanDate() throws FilterParseException { Date now = new Date(); Filter filter = FilterBuilder.create().greaterThan("dog.dob", now).build(); Filter expected = new Filter("dog.dob GT \"" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").format(now) + "\""); // FIXME: format is missing TZ // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testGreaterThanLocalDate() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().greaterThan("dog.dob", now).build(); Filter expected = new Filter("dog.dob GT \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testGreaterThanLocalDateTime() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().greaterThan("dog.dob", now).build(); Filter expected = new Filter("dog.dob GT \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getIntExamples") public void testGreaterThanOrEqualsT_Int(Integer arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GE " + arg); assertThat(filter).isEqualTo(expected); } @ParameterizedTest @MethodSource("getLongExamples") public void testGreaterThanOrEqualsT_Long(Long arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GE " + arg); // values are parsed to integers, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getFloatExamples") public void testGreaterThanOrEqualsT_Float(Float arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GE " + arg); // values are parsed to doubles, use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @ParameterizedTest @MethodSource("getDoubleExamples") public void testGreaterThanOrEqualsT_Double(Double arg) throws FilterParseException { Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.weight", arg).build(); Filter expected = new Filter("dog.weight GE " + arg); assertThat(filter).isEqualTo(expected); } @Test public void testGreaterThanOrEqualsDate() throws FilterParseException { Date now = new Date(); Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.dob", now).build(); Filter expected = new Filter("dog.dob GE \"" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").format(now) + "\""); // FIXME: format is missing TZ // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testGreaterThanOrEqualsLocalDate() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.dob", now).build(); Filter expected = new Filter("dog.dob GE \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testGreaterThanOrEqualsLocalDateTime() throws FilterParseException { LocalDateTime now = LocalDateTime.now(); Filter filter = FilterBuilder.create().greaterThanOrEquals("dog.dob", now).build(); Filter expected = new Filter("dog.dob GE \"" + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } }
4,179
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderEqualsTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class FilterBuilderEqualsTest { @Test public void testEqualToStringString() throws FilterParseException { Filter filter = FilterBuilder.create().equalTo("address.streetAddress", "7714 Sassafrass Way").build(); Filter expected = new Filter("address.streetAddress EQ \"7714 Sassafrass Way\""); assertThat(filter).isEqualTo(expected); } @Test public void testEqualToStringBoolean() throws FilterParseException { Filter filter = FilterBuilder.create().equalTo("address.active", true).build(); Filter expected = new Filter("address.active EQ true"); assertThat(filter).isEqualTo(expected); } @Test public void testEqualToStringDate() throws FilterParseException { Date now = new Date(); Filter filter = FilterBuilder.create().equalTo("date.date", now).build(); Filter expected = new Filter("date.date EQ \"" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").format(now) + "\""); // FIXME: format is missing TZ // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testEqualToStringLocalDate() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().equalTo("date.date", now).build(); Filter expected = new Filter("date.date EQ \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testEqualToStringLocalDateTime() throws FilterParseException { LocalDateTime now = LocalDateTime.now(); Filter filter = FilterBuilder.create().equalTo("date.date", now).build(); Filter expected = new Filter("date.date EQ \"" + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testEqualToStringInteger() throws FilterParseException { int i = 10; Filter filter = FilterBuilder.create().equalTo("int.int", i).build(); Filter expected = new Filter("int.int EQ 10"); assertThat(filter).isEqualTo(expected); } @Test public void testEqualToStringLong() throws FilterParseException { long i = 10l; Filter filter = FilterBuilder.create().equalTo("long.long", i).build(); Filter expected = new Filter("long.long EQ 10"); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testEqualToStringFloat() throws FilterParseException { float i = 10.2f; Filter filter = FilterBuilder.create().equalTo("float.float", i).build(); Filter expected = new Filter("float.float EQ 10.2"); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testEqualToStringDouble() throws FilterParseException { double i = 10.2; Filter filter = FilterBuilder.create().equalTo("double.double", i).build(); Filter expected = new Filter("double.double EQ 10.2"); assertThat(filter).isEqualTo(expected); } @Test public void testEqualNull() throws FilterParseException { Filter filter = FilterBuilder.create().equalNull("null.null").build(); Filter expected = new Filter("null.null EQ null"); assertThat(filter).isEqualTo(expected); } }
4,180
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @Slf4j public class FilterBuilderTest { @Test public void testSimpleAnd() throws FilterParseException { Filter filter = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .and(r -> r.equalTo("name.familyName", "Baggins")) .build(); assertThat(filter).isEqualTo(new Filter("name.givenName EQ \"Bilbo\" AND name.familyName EQ \"Baggins\"")); } @Test public void testSimpleOr() throws FilterParseException { Filter filter = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(r -> r.equalTo("name.familyName", "Baggins")) .build(); assertThat(filter).isEqualTo(new Filter("name.givenName EQ \"Bilbo\" OR name.familyName EQ \"Baggins\"")); } @Test public void testAndOrChain() throws FilterParseException, UnsupportedEncodingException { Filter filter = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(f -> f.equalTo("name.givenName", "Frodo")) .and(f -> f.equalTo("name.familyName", "Baggins")) .build(); Filter expected = new Filter("(name.givenName EQ \"Bilbo\" OR name.givenName EQ \"Frodo\") AND name.familyName EQ \"Baggins\""); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testAndOrChainComplex() throws FilterParseException, UnsupportedEncodingException { Filter filter = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .and(FilterBuilder.create() .equalTo("name.givenName", "Frodo") .and(f -> f.equalTo("name.familyName", "Baggins")) .build()) .build(); Filter expected = new Filter("name.givenName EQ \"Bilbo\" AND (name.givenName EQ \"Frodo\" AND name.familyName EQ \"Baggins\")"); assertThat(filter).isEqualTo(expected); } @Test public void testOrAndChainComplex() throws FilterParseException { Filter filter = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(FilterBuilder.create() .equalTo("name.givenName", "Frodo") .and(f -> f.equalTo("name.familyName", "Baggins")) .build()) .build(); Filter expected = new Filter("name.givenName EQ \"Bilbo\" OR (name.givenName EQ \"Frodo\" AND name.familyName EQ \"Baggins\")"); assertThat(filter).isEqualTo(expected); } @Test public void testComplexAnd() throws FilterParseException { FilterBuilder b1 = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(f -> f.equalTo("name.givenName", "Frodo")) .and(f -> f.equalTo("name.familyName", "Baggins")); FilterBuilder b2 = FilterBuilder.create().equalTo("address.streetAddress", "Underhill") .or(f -> f.equalTo("address.streetAddress", "Overhill")) .and(f -> f.equalTo("address.postalCode", "16803")); Filter filter = FilterBuilder.create().and(b1.build(), b2.build()).build(); Filter expected = new Filter("((name.givenName EQ \"Bilbo\" OR name.givenName EQ \"Frodo\") AND name.familyName EQ \"Baggins\") AND ((address.streetAddress EQ \"Underhill\" OR address.streetAddress EQ \"Overhill\") AND address.postalCode EQ \"16803\")"); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testNot() throws FilterParseException { FilterBuilder b1 = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(f -> f.equalTo("name.givenName", "Frodo")) .and(f -> f.equalTo("name.familyName", "Baggins")); Filter filter = FilterBuilder.create().not(b1.build()).build(); Filter expected = new Filter("NOT((name.givenName EQ \"Bilbo\" OR name.givenName EQ \"Frodo\") AND name.familyName EQ \"Baggins\")"); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testAttributeContains() throws FilterParseException { FilterBuilder b1 = FilterBuilder.create() .equalTo("address.type", "work"); FilterBuilder b2 = FilterBuilder.create() .attributeHas("address", b1.build()); Filter filter = b2.build(); Filter expected = new Filter("address[type EQ \"work\"]"); assertThat(filter).isEqualTo(expected); } @Test public void testAttributeContainsEmbedded() throws FilterParseException { FilterBuilder b1 = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(f -> f.equalTo("name.givenName", "Frodo")) .and(f -> f.equalTo("name.familyName", "Baggins")); FilterBuilder b2 = FilterBuilder.create().attributeHas("address", b1.build()); FilterBuilder b3 = FilterBuilder.create().attributeHas("address", b2.build()); // TODO: I'm not sure why this test exists in the Client // This should probably be a parsing test, and maybe the FilterBuilder should be smarter and throw an // exception when this type Filter is created, instead of just when parsed. String filterString = b3.build().toString(); assertThrows(FilterParseException.class, () -> new Filter(filterString)); } @Test public void testAttributeContainsDeeplyEmbedded() throws FilterParseException { FilterBuilder b1 = FilterBuilder.create() .equalTo("name.givenName", "Bilbo") .or(f -> f.equalTo("name.givenName", "Frodo")) .and(f -> f.equalTo("name.familyName", "Baggins")); FilterBuilder b2 = FilterBuilder.create().attributeHas("address", b1.build()); FilterBuilder b3 = FilterBuilder.create().equalTo("name.giveName", "Gandalf").and(b2.build()); FilterBuilder b4 = FilterBuilder.create().attributeHas("address", b3.build()); assertThrows(FilterParseException.class, () -> new Filter( b4.toString())); } @Test public void complexOrPresent() throws FilterParseException { Filter filter = FilterBuilder.create().or(l -> l.present("name.givenName"), r -> r.present("name.familyName")).build(); assertThat(filter).isEqualTo(new Filter("name.givenName PR OR name.familyName PR")); } @Test public void complexPresentThenOr() throws FilterParseException { Filter filter = FilterBuilder.create().present("name.givenName").or(f -> f.present("name.familyName")).build(); assertThat(filter).isEqualTo(new Filter("name.givenName PR OR name.familyName PR")); } @Test public void expressionThenTwoAnds() { Filter filter = FilterBuilder.create().present("name.givenName").and(l -> l.present("name.familyName"), r -> r.present("name.middleName")).build(); assertThat(filter.getFilter()).isEqualTo("(name.givenName PR AND name.familyName PR) AND name.middleName PR"); } @Test public void expressionThenTwoOrs() { Filter filter = FilterBuilder.create().present("name.givenName").or(l -> l.present("name.familyName"), r -> r.present("name.middleName")).build(); assertThat(filter.getFilter()).isEqualTo("(name.givenName PR OR name.familyName PR) OR name.middleName PR"); } }
4,181
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/InMemoryScimFilterMatcherTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import org.apache.directory.scim.spec.LuckyNumberExtension; import org.apache.directory.scim.spec.resources.*; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.Schemas; import org.assertj.core.api.AbstractAssert; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.util.List; public class InMemoryScimFilterMatcherTest { private final static ScimUser USER1 = user("user1", "User", "One") .setNickName("one") .setAddresses(List.of( new Address() .setType("home") .setPrimary(true) .setStreetAddress("742 Evergreen Terrace") .setRegion("Springfield") .setLocality("Unknown") .setPostalCode("012345") .setCountry("USA"), new Address() .setType("work") .setPrimary(true) .setStreetAddress("101 Reactor Way") .setRegion("Springfield") .setLocality("Unknown") .setPostalCode("012345") .setCountry("USA") )) .addExtension(new LuckyNumberExtension().setLuckyNumber(111)); private final static ScimUser USER2 = user("user2", "User", "Two") .setAddresses(List.of( new Address() .setType("home") .setPrimary(true) .setStreetAddress("11234 Slumvillage Pass") .setRegion("Burfork") .setLocality("CA") .setPostalCode("221134") .setCountry("USA") )) .addExtension(new LuckyNumberExtension().setLuckyNumber(8)); @Test public void userNameMatch() { FilterAssert.assertThat(FilterBuilder.create().equalTo("userName", "user1")) .matches(USER1) .notMatches(USER2); } @Test public void familyNameMatches() { FilterAssert.assertThat(FilterBuilder.create().equalTo("name.familyName", "Two")) .matches(USER2) .notMatches(USER1); } @Test public void startsWithMatches() { FilterAssert.assertThat(FilterBuilder.create().startsWith("name.familyName", "Tw")) .matches(USER2) .notMatches(USER1); } @Test public void endsWithMatches() { FilterAssert.assertThat(FilterBuilder.create().endsWith("name.familyName", "wo")) .matches(USER2) .notMatches(USER1); } @Test public void containsMatches() { FilterAssert.assertThat(FilterBuilder.create().contains("name.familyName", "w")) .matches(USER2) .notMatches(USER1); } @Test public void givenAndFamilyNameMatches() { FilterBuilder filter = FilterBuilder.create() .equalTo("name.givenName", "User") .and(builder -> builder.equalTo("name.familyName", "Two")); FilterAssert.assertThat(filter) .matches(USER2) .notMatches(USER1); } @Test public void familyNameOrMatches() { FilterBuilder filter = FilterBuilder.create() .equalTo("name.familyName", "One") .or(builder -> builder.equalTo("name.familyName", "Two")); FilterAssert.assertThat(filter) .matches(USER2) .matches(USER1); } @Test public void noMatchPassword() { FilterAssert.assertThat(FilterBuilder.create().equalTo("password", "super-secret")) .notMatches(USER1); } @Test public void invertUserNameMatches() { FilterAssert.assertThat(FilterBuilder.create().not(filter -> filter.equalTo("userName", "user1"))) .notMatches(USER1) .matches(USER2); } @Test public void presentAttributeMatches() { FilterAssert.assertThat(FilterBuilder.create().present("nickName")) .matches(USER1) .notMatches(USER2); } @Test public void valuePathExpressionMatches() { FilterAssert.assertThat(FilterBuilder.create().attributeHas("addresses", filter -> filter.equalTo("type", "work"))) .matches(USER1) .notMatches(USER2); } // @Test // public void extensionValueMatches() { // assertThat(FilterBuilder.create().equalTo("luckyNumber", 111)) // .matches(USER1) // .notMatches(USER2); // } @Test public void metaMatches() { FilterAssert.assertThat(FilterBuilder.create().lessThan("meta.lastModified", LocalDateTime.now())) .matches(USER1); FilterAssert.assertThat(FilterBuilder.create().greaterThan("meta.lastModified", LocalDateTime.now().minusYears(1))) .matches(USER1); FilterAssert.assertThat(FilterBuilder.create().greaterThanOrEquals("meta.lastModified", USER1.getMeta().getLastModified())) .matches(USER1); FilterAssert.assertThat(FilterBuilder.create().lessThanOrEquals("meta.lastModified", USER1.getMeta().getLastModified())) .matches(USER1); FilterAssert.assertThat(FilterBuilder.create().equalTo("meta.lastModified", USER1.getMeta().getLastModified())) .matches(USER1); } static class FilterAssert extends AbstractAssert<FilterAssert, Filter> { protected FilterAssert(Filter actual) { super(actual, FilterAssert.class); } public FilterAssert matches(ScimUser user) { isNotNull(); if (!FilterExpressions.inMemory(actual, Schemas.schemaFor(ScimUser.class)).test(user)) { failWithMessage("Expected filter '%s' to match user '%s'", actual.toString(), user); } return this; } public FilterAssert notMatches(ScimUser user) { isNotNull(); if (FilterExpressions.inMemory(actual, Schemas.schemaFor(ScimUser.class)).test(user)) { failWithMessage("Expected filter '%s' to NOT match user '%s'", actual.toString(), user); } return this; } public static FilterAssert assertThat(Filter actual) { return new FilterAssert(actual); } public static FilterAssert assertThat(FilterBuilder actual) { return new FilterAssert(actual.build()); } } private static ScimUser user(String username, String givenName, String familyName) { ScimUser user = new ScimUser() .setUserName(username) .setPassword("super-secret") .setActive(true) .setName(new Name() .setGivenName(givenName) .setFamilyName(familyName) ) .setEmails(List.of( new Email() .setType("work") .setPrimary(true) .setValue(username + "@example.com"), new Email() .setType("personal") .setValue(givenName + "." + familyName + "@example.com") )); user.setMeta(new Meta().setLastModified(LocalDateTime.now())); return user; } }
4,182
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/FilterBuilderNotEqualsTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class FilterBuilderNotEqualsTest { @Test public void testNotnotEqualStringString() throws FilterParseException { Filter filter = FilterBuilder.create().notEqual("address.streetAddress", "7714 Sassafrass Way").build(); Filter expected = new Filter("address.streetAddress NE \"7714 Sassafrass Way\""); assertThat(filter).isEqualTo(expected); } @Test public void testNotnotEqualStringBoolean() throws FilterParseException { Filter filter = FilterBuilder.create().notEqual("address.active", true).build(); Filter expected = new Filter("address.active NE true"); assertThat(filter).isEqualTo(expected); } @Test public void testNotnotEqualStringDate() throws FilterParseException { Date now = new Date(); Filter filter = FilterBuilder.create().notEqual("date.date", now).build(); Filter expected = new Filter("date.date NE \"" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").format(now) + "\""); // FIXME: format is missing TZ // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testNotnotEqualStringLocalDate() throws FilterParseException { LocalDate now = LocalDate.now(); Filter filter = FilterBuilder.create().notEqual("date.date", now).build(); Filter expected = new Filter("date.date NE \"" + DateTimeFormatter.ISO_LOCAL_DATE.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testNotnotEqualStringLocalDateTime() throws FilterParseException { LocalDateTime now = LocalDateTime.now(); Filter filter = FilterBuilder.create().notEqual("date.date", now).build(); Filter expected = new Filter("date.date NE \"" + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(now) + "\""); // TODO: dates are parsed to strings, for now use string comparison assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testNotnotEqualStringInteger() throws FilterParseException { int i = 10; Filter filter = FilterBuilder.create().notEqual("int.int", i).build(); Filter expected = new Filter("int.int NE 10"); assertThat(filter).isEqualTo(expected); } @Test public void testNotnotEqualStringLong() throws FilterParseException { long i = 10l; Filter filter = FilterBuilder.create().notEqual("long.long", i).build(); Filter expected = new Filter("long.long NE 10"); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testNotnotEqualStringFloat() throws FilterParseException { float i = 10.2f; Filter filter = FilterBuilder.create().notEqual("float.float", i).build(); Filter expected = new Filter("float.float NE 10.2"); assertThat(filter.getFilter()).isEqualTo(expected.getFilter()); } @Test public void testNotnotEqualStringDouble() throws FilterParseException { double i = 10.2; Filter filter = FilterBuilder.create().notEqual("double.double", i).build(); Filter expected = new Filter("double.double NE 10.2"); assertThat(filter).isEqualTo(expected); } @Test public void testNotEqualNull() throws FilterParseException { Filter filter = FilterBuilder.create().notEqualNull("null.null").build(); Filter expected = new Filter("null.null NE null"); assertThat(filter).isEqualTo(expected); } }
4,183
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/test/java/org/apache/directory/scim/spec/filter/attribute/AttributeReferenceTest.java
/* * 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. */ package org.apache.directory.scim.spec.filter.attribute; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class AttributeReferenceTest { private static final String USER_NAME = "userName"; private static final String NAME = "name"; private static final String GIVEN_NAME = "givenName"; private static final String NAME_GIVEN_NAME = NAME + "." + GIVEN_NAME; private static final String EMPLOYEE_NUMBER = "employeeNumber"; private static final String CORE_USER_SCHEMA = "urn:ietf:params:scim:schemas:core:2.0:User"; private static final String ENTERPRISE_USER_SCHEMA = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"; protected static final String EXAMPLE_1 = USER_NAME; protected static final String EXAMPLE_2 = USER_NAME.toLowerCase(); protected static final String EXAMPLE_3 = NAME_GIVEN_NAME; protected static final String EXAMPLE_4 = CORE_USER_SCHEMA + ":" + USER_NAME; protected static final String EXAMPLE_5 = CORE_USER_SCHEMA + ":" + USER_NAME.toLowerCase(); protected static final String EXAMPLE_6 = CORE_USER_SCHEMA + ":" + NAME_GIVEN_NAME; protected static final String EXAMPLE_7 = ENTERPRISE_USER_SCHEMA + ":" + EMPLOYEE_NUMBER; @ParameterizedTest @MethodSource("getAttributeReferences") public void testAttributeParsing(String attributeReferenceString, String expectedUrn, String expectedAttriubte) { AttributeReference attributeReference = new AttributeReference(attributeReferenceString); assertEquals(expectedUrn, attributeReference.getUrn()); assertEquals(expectedAttriubte, attributeReference.getFullAttributeName()); } @SuppressWarnings("unused") private static String[][] getAttributeReferences() { return new String[][] { {EXAMPLE_1, null, USER_NAME}, {EXAMPLE_2, null, USER_NAME.toLowerCase()}, {EXAMPLE_3, null, NAME_GIVEN_NAME}, {EXAMPLE_4, CORE_USER_SCHEMA, USER_NAME}, {EXAMPLE_5, CORE_USER_SCHEMA, USER_NAME.toLowerCase()}, {EXAMPLE_6, CORE_USER_SCHEMA, NAME_GIVEN_NAME}, {EXAMPLE_7, ENTERPRISE_USER_SCHEMA, EMPLOYEE_NUMBER} }; } }
4,184
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/validator/UrnValidator.java
/* * 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. */ package org.apache.directory.scim.spec.validator; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; public class UrnValidator implements ConstraintValidator<Urn, String> { private static final String URN_RFC2141_REGEX = "^urn:[a-zA-Z0-9][a-zA-Z0-9-]{0,31}:(?:[a-zA-Z0-9()+,\\-.:=@;$_!*']|%[0-9a-fA-F]{2})+$"; @Override public void initialize(Urn validator) { } @Override public boolean isValid(String urn, ConstraintValidatorContext context) { if (urn == null || urn.isEmpty()) { return true; } return urn.matches(URN_RFC2141_REGEX); } }
4,185
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/validator/Urn.java
/* * 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. */ package org.apache.directory.scim.spec.validator; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import jakarta.validation.Constraint; import jakarta.validation.Payload; @Constraint(validatedBy = UrnValidator.class) @Target( { METHOD, FIELD, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface Urn { String message() default "The urn is malformed"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
4,186
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/extension/EnterpriseExtension.java
/* * 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. */ package org.apache.directory.scim.spec.extension; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema.Attribute.Mutability; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) @ScimExtensionType(required = false, name = "EnterpriseUser", id = EnterpriseExtension.URN, description = "Attributes commonly used in representing users that belong to, or act on behalf of, a business or enterprise.") @Data public class EnterpriseExtension implements ScimExtension { private static final long serialVersionUID = -6850246976790442980L; public static final String URN = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"; @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data public static class Manager implements Serializable { private static final long serialVersionUID = -7930518578899296192L; @ScimAttribute(description = "The \"id\" of the SCIM resource representing the user's manager. RECOMMENDED.") @XmlElement private String value; @ScimAttribute(description = "The URI of the SCIM resource representing the User's manager. RECOMMENDED.") @XmlElement(name="$ref") private String ref; @ScimAttribute(mutability = Mutability.READ_ONLY, description = "he displayName of the user's manager. This attribute is OPTIONAL.") @XmlElement private String displayName; } @ScimAttribute(description = "A string identifier, typically numeric or alphanumeric, assigned to a person, typically based on order of hire or association with an organization.") @XmlElement private String employeeNumber; @ScimAttribute(description = "Identifies the name of a cost center.") @XmlElement private String costCenter; @ScimAttribute(description = "Identifies the name of an organization.") @XmlElement private String organization; @ScimAttribute(description = "Identifies the name of a division.") @XmlElement private String division; @ScimAttribute(description = "Identifies the name of a department.") @XmlElement private String department; @ScimAttribute(description = "The user's manager. A complex type that optionally allows service providers to represent organizational hierarchy by referencing the \"id\" attribute of another User.") @XmlElement private Manager manager; @Override public String getUrn() { return URN; } }
4,187
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Photo.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; import lombok.EqualsAndHashCode; /** * Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a> * */ @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data @EqualsAndHashCode(callSuper=false) public class Photo implements Serializable, TypedAttribute { private static final long serialVersionUID = 8821620834716156789L; @XmlElement @ScimAttribute(description="URL of a photo of the User.", referenceTypes={"external"}) String value; @XmlElement(nillable=true) @ScimAttribute(canonicalValueList={"photo", "thumbnail"}, description="A label indicating the attribute's function; e.g., 'photo' or 'thumbnail'.") String type; @XmlElement @ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.") String display; @XmlElement @ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.") Boolean primary = false; }
4,188
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/ScimResource.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import com.fasterxml.jackson.annotation.JsonAnyGetter; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.annotation.ScimResourceType; import org.apache.directory.scim.spec.exception.InvalidExtensionException; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; /** * This class defines the attributes shared by all SCIM resources. It also * provides BVF annotations to allow validation of the POJO. * * @author smoyer1 */ @Data @EqualsAndHashCode(callSuper = true) @XmlAccessorType(XmlAccessType.NONE) public abstract class ScimResource extends BaseResource<ScimResource> implements Serializable { private static final long serialVersionUID = 3673404125396687366L; private static final Logger LOG = LoggerFactory.getLogger(ScimResource.class); @XmlElement @NotNull @ScimAttribute(returned = Returned.ALWAYS) Meta meta; @XmlElement @Size(min = 1) @ScimAttribute(required = true, returned = Returned.ALWAYS, description = "A unique identifier for a SCIM resource as defined by the service provider.") String id; @XmlElement @ScimAttribute String externalId; // TODO - Figure out JAXB equivalent of JsonAnyGetter and JsonAnySetter // (XmlElementAny?) private Map<String, ScimExtension> extensions = new LinkedHashMap<>(); private final String baseUrn; private final String resourceType; public ScimResource(String urn, String resourceType) { super(urn); this.baseUrn = urn; this.resourceType = resourceType; ScimResourceType resourceTypeAnnotation = getClass().getAnnotation(ScimResourceType.class); if (resourceTypeAnnotation != null) { this.meta = new Meta().setResourceType(resourceTypeAnnotation.id()); } } /** * Add an extension to the ScimResource * @param extension the scim extension * @throws InvalidExtensionException if the ScimExtension passed in is improperly configured. */ public ScimResource addExtension(ScimExtension extension) { ScimExtensionType[] se = extension.getClass().getAnnotationsByType(ScimExtensionType.class); if (se.length != 1) { throw new InvalidExtensionException("Registered extensions must have an ScimExtensionType annotation"); } String extensionUrn = se[0].id(); extensions.put(extensionUrn, extension); addSchema(extensionUrn); return this; } public ScimExtension getExtension(String urn) { return extensions.get(urn); } /** * Returns the scim extension of a particular class * @param extensionClass * @return * @throws InvalidExtensionException if the ScimExtension passed in is improperly configured. */ @SuppressWarnings("unchecked") public <T> T getExtension(Class<T> extensionClass) { ScimExtensionType se = lookupScimExtensionType(extensionClass); return (T) extensions.get(se.id()); } private <T> ScimExtensionType lookupScimExtensionType(Class<T> extensionClass) { ScimExtensionType[] se = extensionClass.getAnnotationsByType(ScimExtensionType.class); if (se.length != 1) { throw new InvalidExtensionException("Registered extensions must have an ScimExtensionType annotation"); } return se[0]; } public String getBaseUrn() { return baseUrn; } @JsonAnyGetter public Map<String, ScimExtension> getExtensions() { return extensions; } public ScimExtension removeExtension(String urn) { return extensions.remove(urn); } @SuppressWarnings("unchecked") public <T> T removeExtension(Class<T> extensionClass) { ScimExtensionType se = lookupScimExtensionType(extensionClass); return (T) extensions.remove(se.id()); } }
4,189
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Email.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; import lombok.EqualsAndHashCode; /** * Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a> * */ @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data @EqualsAndHashCode(callSuper=false) public class Email implements Serializable, TypedAttribute { private static final long serialVersionUID = -7914234516870440784L; @XmlElement(nillable=true) @ScimAttribute(canonicalValueList={"work", "home", "other" }, description="A label indicating the attribute's function; e.g., 'work' or 'home'.") String type; @XmlElement @ScimAttribute(description="E-mail addresses for the user. The value SHOULD be canonicalized by the Service Provider, e.g. bjensen@example.com instead of bjensen@EXAMPLE.COM. Canonical Type values of work, home, and other.") String value; @XmlElement @ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.") String display; @XmlElement @ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.") Boolean primary = false; }
4,190
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/ScimResourceWithOptionalId.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import lombok.Data; import lombok.EqualsAndHashCode; /** * This class overrides the required id element in ScimResource for use as a * base class for some of the odd SCIM resources. * * @author crh5255 */ @Data @EqualsAndHashCode(callSuper = true) @XmlAccessorType(XmlAccessType.NONE) public abstract class ScimResourceWithOptionalId extends ScimResource { private static final long serialVersionUID = -379538554565387791L; @XmlElement String id; public ScimResourceWithOptionalId(String urn, String resourceType) { super(urn, resourceType); } }
4,191
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/ScimUser.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimResourceType; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.ResourceReference; import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned; import org.apache.directory.scim.spec.schema.Schema.Attribute.Uniqueness; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @Data @ToString(callSuper = true, exclude = {"password"}) @EqualsAndHashCode(callSuper = true, exclude = {"password"}) @ScimResourceType(id = ScimUser.RESOURCE_NAME, name = ScimUser.RESOURCE_NAME, schema = ScimUser.SCHEMA_URI, description = "Top level ScimUser", endpoint = "/Users") @XmlRootElement(name = ScimUser.RESOURCE_NAME) @XmlAccessorType(XmlAccessType.NONE) public class ScimUser extends ScimResource implements Serializable { private static final long serialVersionUID = -2306547717245071997L; public static final String RESOURCE_NAME = "User"; public static final String SCHEMA_URI = "urn:ietf:params:scim:schemas:core:2.0:User"; @XmlElement @ScimAttribute(description="A Boolean value indicating the User's administrative status.") Boolean active = true; @XmlElement @ScimAttribute(description="A physical mailing address for this User, as described in (address Element). Canonical Type Values of work, home, and other. The value attribute is a complex type with the following sub-attributes.") List<Address> addresses; @XmlElement @ScimAttribute(description="The name of the User, suitable for display to end-users. The name SHOULD be the full name of the User being described if known") String displayName; @XmlElement @ScimAttribute(description="E-mail addresses for the user. The value SHOULD be canonicalized by the Service Provider, e.g. bjensen@example.com instead of bjensen@EXAMPLE.COM. Canonical Type values of work, home, and other.") List<Email> emails; @XmlElement @ScimAttribute(description="An entitlement may be an additional right to a thing, object, or service") List<Entitlement> entitlements; @XmlElement @ScimAttribute(description="A list of groups that the user belongs to, either thorough direct membership, nested groups, or dynamically calculated") List<ResourceReference> groups; @XmlElement @ScimAttribute(description="Instant messaging address for the User.") List<Im> ims; @XmlElement @ScimAttribute(description="Used to indicate the User's default location for purposes of localizing items such as currency, date time format, numerical representations, etc.") String locale; @XmlElement @ScimAttribute(description="The components of the user's real name. Providers MAY return just the full name as a single string in the formatted sub-attribute, or they MAY return just the individual component attributes using the other sub-attributes, or they MAY return both. If both variants are returned, they SHOULD be describing the same name, with the formatted name indicating how the component attributes should be combined.") Name name; @XmlElement @ScimAttribute(description="The casual way to address the user in real life, e.g.'Bob' or 'Bobby' instead of 'Robert'. This attribute SHOULD NOT be used to represent a User's username (e.g. bjensen or mpepperidge)") String nickName; @XmlElement @ScimAttribute(returned = Returned.NEVER, description="The User's clear text password. This attribute is intended to be used as a means to specify an initial password when creating a new User or to reset an existing User's password.") String password; @XmlElement @ScimAttribute(description="Phone numbers for the User. The value SHOULD be canonicalized by the Service Provider according to format in RFC3966 e.g. 'tel:+1-201-555-0123'. Canonical Type values of work, home, mobile, fax, pager and other.") List<PhoneNumber> phoneNumbers; @XmlElement @ScimAttribute(description="URLs of photos of the User.") List<Photo> photos; @XmlElement @ScimAttribute(description="A fully qualified URL to a page representing the User's online profile", referenceTypes={"external"}) String profileUrl; @XmlElement @ScimAttribute(description="Indicates the User's preferred written or spoken language. Generally used for selecting a localized User interface. e.g., 'en_US' specifies the language English and country US.") String preferredLanguage; @XmlElement @ScimAttribute(description="A list of roles for the User that collectively represent who the User is; e.g., 'Student', 'Faculty'.") List<Role> roles; @XmlElement @ScimAttribute(description="The User's time zone in the 'Olson' timezone database format; e.g.,'America/Los_Angeles'") String timezone; @XmlElement @ScimAttribute(description="The user's title, such as \"Vice President.\"") String title; @XmlElement @ScimAttribute(required=true, uniqueness=Uniqueness.SERVER, description="Unique identifier for the User typically used by the user to directly authenticate to the service provider. Each User MUST include a non-empty userName value. This identifier MUST be unique across the Service Consumer's entire set of Users. REQUIRED") String userName; @XmlElement @ScimAttribute(description="Used to identify the organization to user relationship. Typical values used might be 'Contractor', 'Employee', 'Intern', 'Temp', 'External', and 'Unknown' but any value may be used.") String userType; @XmlElement @ScimAttribute(description="A list of certificates issued to the User.") List<X509Certificate> x509Certificates; public ScimUser() { super(SCHEMA_URI, RESOURCE_NAME); } public Optional<Address> getPrimaryAddress() { if (addresses == null) { return Optional.empty(); } return addresses.stream() .filter(Address::getPrimary) .findFirst(); } public Optional<Email> getPrimaryEmailAddress() { if (emails == null) { return Optional.empty(); } return emails.stream() .filter(Email::getPrimary) .findFirst(); } public Optional<PhoneNumber> getPrimaryPhoneNumber() { if (phoneNumbers == null) { return Optional.empty(); } return phoneNumbers.stream() .filter(PhoneNumber::getPrimary) .findFirst(); } @Override public ScimUser setSchemas(Set<String> schemas) { return (ScimUser) super.setSchemas(schemas); } @Override public ScimUser setMeta(@NotNull Meta meta) { return (ScimUser) super.setMeta(meta); } @Override public ScimUser setId(@Size(min = 1) String id) { return (ScimUser) super.setId(id); } @Override public ScimUser setExternalId(String externalId) { return (ScimUser) super.setExternalId(externalId); } @Override public ScimUser setExtensions(Map<String, ScimExtension> extensions) { return (ScimUser) super.setExtensions(extensions); } @Override public ScimUser addSchema(String urn) { return (ScimUser) super.addSchema(urn); } @Override public ScimUser addExtension(ScimExtension extension) { return (ScimUser) super.addExtension(extension); } }
4,192
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/ScimExtension.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "ScimExtension") public interface ScimExtension extends Serializable { String getUrn(); }
4,193
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Address.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; import lombok.EqualsAndHashCode; /** * Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a> * */ @XmlType(name = "address") @XmlAccessorType(XmlAccessType.NONE) @Data @EqualsAndHashCode(callSuper=false) public class Address implements Serializable, TypedAttribute { private static final long serialVersionUID = 3579689988186914163L; @XmlElement @ScimAttribute(canonicalValueList={"work", "home", "other"}, description="A label indicating the attribute's function; e.g., 'aim', 'gtalk', 'mobile' etc.") String type; @XmlElement @ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.") String display; @XmlElement @ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.") Boolean primary = false; @ScimAttribute(description="The two letter ISO 3166-1 alpha-2 country code") @XmlElement private String country; @ScimAttribute(description="The full mailing address, formatted for display or use with a mailing label. This attribute MAY contain newlines.") @XmlElement private String formatted; @ScimAttribute(description="The city or locality component.") @XmlElement private String locality; @ScimAttribute(description="The zipcode or postal code component.") @XmlElement private String postalCode; @ScimAttribute(description="The state or region component.") @XmlElement private String region; @ScimAttribute(description="The full street address component, which may include house number, street name, PO BOX, and multi-line extended street address information. This attribute MAY contain newlines.") @XmlElement private String streetAddress; }
4,194
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/X509Certificate.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; /** * Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a> * */ @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data public class X509Certificate implements Serializable, TypedAttribute { private static final long serialVersionUID = 374273508404129850L; @XmlElement(nillable=true) @ScimAttribute(description="A label indicating the attribute's function.") String type; @XmlElement @ScimAttribute(description="The value of a X509 certificate.") String value; @XmlElement @ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.") String display; @XmlElement @ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.") Boolean primary = false; }
4,195
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Im.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; import lombok.EqualsAndHashCode; /** * Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a> * */ @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data @EqualsAndHashCode(callSuper=false) public class Im implements Serializable, TypedAttribute { private static final long serialVersionUID = 6324188935390255346L; @XmlElement(nillable=true) @ScimAttribute(canonicalValueList={"aim", "qtalk", "icq", "xmpp", "msn", "skype", "qq", "yahoo"}, description="A label indicating the attribute's function; e.g., 'aim', 'gtalk', 'mobile' etc.") String type; @XmlElement @ScimAttribute(description="Instant messaging address for the User.") String value; @XmlElement @ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.") String display; @XmlElement @ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.") Boolean primary = false; }
4,196
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Name.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.annotation.ScimAttribute; @Data @EqualsAndHashCode(callSuper=false,exclude={"formatted"}) @XmlType(name = "name", propOrder = { "formatted", "familyName", "givenName", "middleName", "honorificPrefix", "honorificSuffix" }) @XmlAccessorType(XmlAccessType.NONE) public class Name implements Serializable { private static final long serialVersionUID = -2761413543859555141L; @XmlElement @ScimAttribute(description="The full name, including all middle names, titles, and suffixes as appropriate, formatted for display (e.g. Ms. Barbara J Jensen, III.).") String formatted; @XmlElement @ScimAttribute(description="The family name of the User, or Last Name in most Western languages (e.g. Jensen given the full name Ms. Barbara J Jensen, III.).") String familyName; @XmlElement @ScimAttribute(description="The given name of the User, or First Name in most Western languages (e.g. Barbara given the full name Ms. Barbara J Jensen, III.).") String givenName; @XmlElement @ScimAttribute(description="The middle name(s) of the User (e.g. Robert given the full name Ms. Barbara J Jensen, III.).") String middleName; @XmlElement @ScimAttribute(description="The honorific prefix(es) of the User, or Title in most Western languages (e.g. Ms. given the full name Ms. Barbara J Jensen, III.).") String honorificPrefix; @XmlElement @ScimAttribute(description="The honorific suffix(es) of the User, or Suffix in most Western languages (e.g. III. given the full name Ms. Barbara J Jensen, III.).") String honorificSuffix; }
4,197
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/ScimGroup.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimResourceType; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.ResourceReference; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) @ScimResourceType(id = ScimGroup.RESOURCE_NAME, name = ScimGroup.RESOURCE_NAME, schema = ScimGroup.SCHEMA_URI, description = "Top level ScimGroup", endpoint = "/Groups") @XmlRootElement(name = ScimGroup.RESOURCE_NAME) @XmlAccessorType(XmlAccessType.NONE) public class ScimGroup extends ScimResource implements Serializable { private static final long serialVersionUID = 4424638498347469070L; public static final String RESOURCE_NAME = "Group"; public static final String SCHEMA_URI = "urn:ietf:params:scim:schemas:core:2.0:Group"; @XmlElement @ScimAttribute(description="A human-readable name for the Group.", required=true) String displayName; @XmlElement @ScimAttribute(description = "A list of members of the Group.") List<ResourceReference> members; public ScimGroup addMember(ResourceReference resourceReference) { if (members == null) { members = new ArrayList<>(); } members.add(resourceReference); return this; } public ScimGroup() { super(SCHEMA_URI, RESOURCE_NAME); } @Override public ScimGroup setSchemas(Set<String> schemas) { return (ScimGroup) super.setSchemas(schemas); } @Override public ScimGroup setMeta(@NotNull Meta meta) { return (ScimGroup) super.setMeta(meta); } @Override public ScimGroup setId(@Size(min = 1) String id) { return (ScimGroup) super.setId(id); } @Override public ScimGroup setExternalId(String externalId) { return (ScimGroup) super.setExternalId(externalId); } @Override public ScimGroup setExtensions(Map<String, ScimExtension> extensions) { return (ScimGroup) super.setExtensions(extensions); } @Override public ScimGroup addSchema(String urn) { return (ScimGroup) super.addSchema(urn); } @Override public ScimGroup addExtension(ScimExtension extension) { return (ScimGroup) super.addExtension(extension); } }
4,198
0
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec
Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Role.java
/* * 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. */ package org.apache.directory.scim.spec.resources; import java.io.Serializable; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; import lombok.EqualsAndHashCode; /** * Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a> * */ @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data @EqualsAndHashCode(callSuper=false) public class Role implements Serializable, TypedAttribute { private static final long serialVersionUID = -2781839189814966670L; @XmlElement(nillable=true) @ScimAttribute(description="A label indicating the attribute's function.") String type; @XmlElement @ScimAttribute(description="The value of a role.") String value; @XmlElement @ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.") String display; @XmlElement @ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.") Boolean primary = false; }
4,199