1. 變更授權規則
編輯 /etc/pam.d/su 檔,找到 auth required 這個項目,原來的值可能如下:
auth required pam_wheel.so trust group=wheel
auth required pam_wheel.so use_uid
假設想要 user1 和 user2 可以相互切換,那麼執行如下指令:
usermod -a -G wheel user1 usermod -a -G wheel user2
auth required pam_wheel.so trust group=wheel
auth required pam_wheel.so use_uid
usermod -a -G wheel user1 usermod -a -G wheel user2
1 apply plugin: 'java' 2 apply plugin: 'war' 3 4 sourceCompatibility = 1.8 5 version = '1.0' 6 7 sourceSets { 8 main { 9 java { 10 srcDirs = ['src/main/java'] 11 } 12 resources { 13 srcDirs = ['config'] 14 } 15 } 16 test { 17 java { 18 srcDirs = ['src/test/java'] 19 } 20 } 21 } 22 23 buildDir = 'out' 24 25 repositories { 26 maven { url "http://maven.springframework.org/milestone" } 27 maven { url "http://repo.maven.apache.org/maven2" } 28 maven { url "http://repo1.maven.org/maven2/" } 29 maven { url "http://amateras.sourceforge.jp/mvn/" } 30 mavenCentral() 31 } 32 33 configurations.all { 34 exclude group: 'org.freemarker', module: 'freemarker' 35 exclude group: 'javax.el', module: 'el-api' 36 exclude group: 'xerces', module: 'xercesImpl' 37 exclude group: 'xml-apis', module: 'xml-apis' 38 exclude group: 'jboss', module: 'javassist' 39 exclude group: 'org.apache.tomcat.embed', module: 'tomcat-embed-core' 40 exclude group: 'org.apache.tomcat.embed', module: 'tomcat-embed-el' 41 exclude group: 'org.apache.tomcat.embed', module: 'tomcat-embed-websocket' 42 exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc' 43 exclude group: 'org.apache.tomcat', module: 'tomcat-juli' 44 exclude group: 'org.apache.ant', module: 'ant' 45 46 resolutionStrategy { 47 force group: 'org.apache.ant', name: 'ant', version: '1.10.1' 48 } 49 } 50 51 dependencies { 52 def tomcatVersion = '9.0.0.M22' 53 def springVersion = '4.3.10.RELEASE' 54 def springBootVersion = '1.5.4.RELEASE' 55 def hibernateVersion = '5.2.10.Final' 56 def hibernateValidatorVersion = '6.0.1.Final' 57 58 compile fileTree(dir: 'library', include: ['*.jar']) 59 60 testCompile group: 'junit', name: 'junit', version: '4.+' 61 62 //javax 63 compile group: 'javax.inject', name: 'javax.inject', version: '1' 64 compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0' 65 compile group: 'javax.activation', name: 'activation', version: '1.1.1' 66 67 //spring framework 68 compile group: 'org.springframework', name: 'spring-context', version: "$springVersion" 69 compile group: 'org.springframework', name: 'spring-test', version: "$springVersion" 70 71 //spring boot 72 compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: "${springBootVersion}" 73 74 //Others 75 compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.7.0' 76 }
Properties prop = new Properties(); URL url = this.getClass().getClassLoader().getResource("application.properties"); URI uri = url.toURI(); File file = new File(uri); InputStream is = new FileInputStream(file); prop.load(is); is.close(); FileOutputStream os = new FileOutputStream(file); prop.setProperty("myKey", myValue); prop.store(os, null); os.close();
@PropertySource("classpath:application.properties")
@Value("${myKey}")
private String myValue;
@Inject private StandardEnvironment environment; ... MutablePropertySources propertySources = environment.getPropertySources(); PropertySource resourcePropertySource = propertySources.get("class path resource [application.properties]"); URL url = this.getClass().getClassLoader().getResource("application.properties"); URI uri = url.toURI(); File file = new File(uri); InputStream is = new FileInputStream(file); Properties prop = new Properties(); prop.load(is); is.close(); propertySources.replace("class path resource [application.properties]", new PropertiesPropertySource("class path resource [application.properties]", prop));
1 @Data 2 public class MyBeanEvent extends ApplicationEvent { 3 private String msg; 4 5 public MyBeanEvent(Object source) { 6 super(source); 7 8 this.msg = (String) source; 9 } 10 }
1 @Component 2 public class MyPublisher { 3 @Inject 4 private ApplicationContext context; 5 6 public void publish(String msg) { 7 context.publishEvent(new MyBeanEvent(msg)); 8 } 9 }
1 @Component 2 public class MyListener implements ApplicationListener<MyBeanEvent> { 3 4 @Override 5 public void onApplicationEvent(MyBeanEvent event) { 6 System.out.println("listen: " + event.getMsg()); 7 } 8 }
1 @Configuration 2 @ComponentScan("idv.steven.info.tse") 3 public class MyEventConfig { 4 5 }
1 public class MyTestMain { 2 3 public static void main(String[] args) { 4 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyEventConfig.class); 5 MyPublisher publisher = context.getBean(MyPublisher.class); 6 publisher.publish("Hello World"); 7 context.close(); 8 } 9 }
ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0271E: 未捕捉到應用程式中Servlet [application] 產生的init() 異常狀況:java.lang.IncompatibleClassChangeError at org.dom4j.tree.AbstractElement.setAttributes(AbstractElement.java:505) at org.dom4j.io.SAXContentHandler.addAttributes(SAXContentHandler.java:916) at org.dom4j.io.SAXContentHandler.startElement(SAXContentHandler.java:249) at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source) at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
webapp E com.ibm.ws.webcontainer.webapp.WebApp initializeExtensionProcessors SRVE0280E: 在 Factory [com.ibm.ws.jsp.webcontainerext.ws.WASJSPExtensionFactory@f87c2d7d] 中,延伸規格處理器無法起始設定:java.lang.ClassCastException: org.apache.el.ExpressionFactoryImpl incompatible with javax.el.ExpressionFactory at javax.el.ExpressionFactory.newInstance(ExpressionFactory.java:210) at javax.el.ExpressionFactory.newInstance(ExpressionFactory.java:118) at com.ibm.ws.jsp.configuration.JspConfiguration.<init>(JspConfiguration.java:63) at com.ibm.ws.jsp.configuration.JspConfigurationManager.createJspConfiguration(JspConfigurationManager.java:202) at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfTagFiles(TagLibraryCache.java:444) at com.ibm.ws.jsp.taglib.TagLibraryCache.<init>(TagLibraryCache.java:117) at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionProcessor.<init>(AbstractJSPExtensionProcessor.java:215) at com.ibm.ws.jsp.webcontainerext.ws.WASJSPExtensionProcessor.<init>(WASJSPExtensionProcessor.java:81) at com.ibm.ws.jsp.webcontainerext.ws.WASJSPExtensionFactory.createProcessor(WASJSPExtensionFactory.java:267) at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionFactory.createExtensionProcessor(AbstractJSPExtensionFactory.java:76) at com.ibm.ws.webcontainer.webapp.WebApp.initializeExtensionProcessors(WebApp.java:1408)
Caused by: javax.xml.parsers.FactoryConfigurationError: Provider javax.xml.parsers.DocumentBuilderFactory could not be instantiated: java.util.ServiceConfigurationError: javax.xml.parsers.DocumentBuilderFactory: Provider org.apache.xerces.jaxp.DocumentBuilderFactoryImpl not a subtype at javax.xml.parsers.DocumentBuilderFactory.newInstance(Unknown Source) at com.ibm.websphere.product.utils.SimpleXMLParser.getDocumentBuilderWithEntityResolver(SimpleXMLParser.java:760) at com.ibm.websphere.product.utils.SimpleXMLParser.<init>(SimpleXMLParser.java:198) at com.ibm.websphere.product.utils.SimpleXMLParser.<init>(SimpleXMLParser.java:176) at com.ibm.websphere.product.metadata.im.IMMetadata.parseInstalledXmlFile(IMMetadata.java:422) at com.ibm.websphere.product.metadata.im.IMMetadata.parseInstallRegistryFiles(IMMetadata.java:364)
Exception occurred while the JNDI NamingManager was processing a javax.naming.Reference object. [Root exception is javax.xml.stream.FactoryConfigurationError: Provider javax.xml.stream.XMLInputFactory could not be instantiated: java.util.ServiceConfigurationError: javax.xml.stream.XMLInputFactory: Provider com.ctc.wstx.stax.WstxInputFactory not a subtype]
Caused by: java.lang.NoSuchMethodError: javax.persistence.spi.PersistenceUnitInfo.getValidationMode()Ljavax/persistence/ValidationMode; at org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor.getValidationMode(PersistenceUnitInfoDescriptor.java:88) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.mergeSettings(EntityManagerFactoryBuilderImpl.java:454) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:199) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:163)
public interface UsersDAO extends PagingAndSortingRepository<Users, String> { public List<Users> findByEmail(String email); //public Page<Users> findAll(Pageable p); }
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebInitializer.class, RootConfig.class, JpaConfig.class, MvcConfig.class }) @ActiveProfiles("TEST") public class UserDAOTest { @Autowired private UsersDAO dao; @Transactional @Test public void testFindAll() { Pageable p = new PageRequest(0, 5); Page<Users> all = dao.findAll(p); all.forEach(u -> System.out.println(u.toString())); } }
@Transactional @Test public void testFindByEmail() { Users user = dao.findByEmail("hi.steven@gmail.com"); assertNotNull(user); System.out.println(user.toString()); }
1 @Entity 2 @Table( 3 name="APPOINTMENT", 4 uniqueConstraints = { 5 @UniqueConstraint(columnNames = "SYSID") 6 }) 7 @Data 8 public class Appointment implements Serializable { 9 private static final long serialVersionUID = -3781642274581820116L; 10 11 @Id 12 @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_APPOINTMENT") 13 @SequenceGenerator(name="SEQ_APPOINTMENT", sequenceName="SEQ_APPOINTMENT", initialValue=1, allocationSize=1) 14 private Long sysid; 15 16 @ManyToOne(fetch = FetchType.LAZY) 17 @JoinColumn(name = "EMAIL", insertable = false, updatable = false) 18 private Users users; 19 20 @Column(name = "NAME", length = 30) 21 private String name; 22 23 @ManyToOne(fetch = FetchType.LAZY) 24 @JoinColumn(name = "RESTAURANT_SYSID", insertable = false, updatable = false) 25 private Restaurant restaurant; 26 27 @Column(name = "DESCRIPTION", length = 500) 28 private String description; 29 30 @Column(name = "PHOTO") 31 private byte[] photo; 32 33 @Column(name = "PEOPLE") 34 private Integer people; 35 36 @Column(name = "WILLPAY") 37 private Integer willPay; 38 39 @Column(name = "PAYKIND", length = 2) 40 private String payKind; 41 42 @Column(name = "CANCEL", length = 1) 43 private String cancel; 44 45 @Column(name = "HTIME") 46 private Date htime; 47 48 @Column(name = "CTIME") 49 private Date ctime; 50 51 @Override 52 public String toString() { 53 return "Appointment [sysid=" + sysid + ", name=" + name + ", description=" + description + ", photo=" 54 + Arrays.toString(photo) + ", people=" + people + ", willPay=" + willPay + ", payKind=" + payKind 55 + ", cancel=" + cancel + ", htime=" + htime + ", ctime=" + ctime + "]"; 56 } 57 58 @ManyToMany(fetch = FetchType.LAZY) 59 @JoinTable(name = "PARTICIPANT", 60 joinColumns = { @JoinColumn(name = "APPOINTMENT_SYSID") }, 61 inverseJoinColumns = { @JoinColumn (name = "EMAIL") }) 62 private List<Users> particpants; 63 }
@Test public void testCreate() throws IOException { //讀檔 Path path = Paths.get("E:/55047183.jpg"); byte[] photo = Files.readAllBytes(path); //寫入DB Appointment appointment = new Appointment(); Users user = daoUsers.findOne("hi.steven@gmail.com"); Restaurant restaurant = daoRestaurant.find(2L); appointment.setUsers(user); appointment.setName("除夕圍爐"); appointment.setRestaurant(restaurant); appointment.setDescription("除夕找人聊天"); appointment.setPhoto(photo); appointment.setPeople(2); appointment.setWillPay(500); appointment.setPayKind("A"); appointment.setCancel("N"); appointment.setHtime(Calendar.getInstance().getTime()); appointment.setCtime(Calendar.getInstance().getTime()); int count = daoApp.create(appointment); assertEquals(1, count); }
public List<Appointment> find(Users user) { TypedQuery<Appointment> query = manager.createQuery("select a from Appointment a where a.users = :user ", Appointment.class); query.setParameter("user", user); return query.getResultList(); }
@Transactional @Test public void testFindUser() throws IOException { Users user = daoUsers.findOne("hi.steven@gmail.com"); List<Appointment> app = daoApp.find(user); for(Appointment a:app) { System.out.println(a.getParticpants().toString()); } }
<Context docBase="Party" path="/Party" reloadable="true" source="org.eclipse.jst.jee.server:Party" />
<Context docBase="Party" path="/Party" reloadable="true" source="org.eclipse.jst.jee.server:Party"> <Resource auth="Container" driverClassName="oracle.jdbc.OracleDriver" maxIdle="10" maxTotal="20" maxWaitMillis="-1" name="jdbc/DemoDB" password="passw0rd" type="javax.sql.DataSource" url="jdbc:oracle:thin:@192.168.0.102:1521:DemoDB" username="steven"/> </Context>
<resource-ref> <description>oracleDB</description> <res-ref-name>jdbc/DemoDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { RootConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { MvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
1 @Configuration 2 @ComponentScan( 3 basePackages = {"idv.steven.invitation"}, 4 includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class), 5 excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) 6 ) 7 @Log4j 8 public class RootConfig { 9 10 @Bean 11 @Profile("PROD") 12 public JndiObjectFactoryBean jndiObjectFactoryBean() { 13 JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean(); 14 jndiObjectFB.setJndiName("jdbc/DemoDB"); 15 jndiObjectFB.setResourceRef(true); 16 jndiObjectFB.setProxyInterface(javax.sql.DataSource.class); 17 18 return jndiObjectFB; 19 } 20 21 @Bean 22 @Profile("TEST") 23 public DataSource dataSource() { 24 BasicDataSource ds = new BasicDataSource(); 25 ds.setDriverClassName("oracle.jdbc.OracleDriver"); 26 ds.setUrl("jdbc:oracle:thin:@192.168.0.102:1521:DemoDB"); 27 ds.setUsername("steven"); 28 ds.setPassword("passw0rd"); 29 ds.setInitialSize(5); 30 31 return ds; 32 } 33 }
<context-param> <param-name>spring.profiles.active</param-name> <param-value>PROD</param-value> </context-param>
1 @Configuration 2 @EnableTransactionManagement 3 @EnableJpaRepositories ( 4 basePackages = { "idv.steven.invitation.database.dao" }, 5 entityManagerFactoryRef = "entityManagerFactory", 6 transactionManagerRef = "jpaTransactionManager" 7 ) 8 public class JpaConfig { 9 @Autowired(required=false) 10 private DataSource dataSource; 11 12 @Autowired(required=false) 13 private JndiObjectFactoryBean jndiObjectFB; 14 15 @Bean 16 public JpaVendorAdapter jpaVendorAdapter() { 17 HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); 18 19 adapter.setDatabase(Database.ORACLE); 20 adapter.setShowSql(true); 21 adapter.setGenerateDdl(false); 22 adapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect"); 23 24 return adapter; 25 } 26 27 @Bean 28 public PlatformTransactionManager jpaTransactionManager() { 29 JpaTransactionManager tm = new JpaTransactionManager(); 30 tm.setEntityManagerFactory(this.entityManagerFactory().getObject()); 31 32 return tm; 33 } 34 35 @Bean 36 public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 37 LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); 38 if (dataSource == null) 39 emf.setDataSource((DataSource) jndiObjectFB.getObject()); 40 else 41 emf.setDataSource(dataSource); 42 emf.setPackagesToScan(new String[] { "idv.steven.invitation.database.entity" }); 43 emf.setJpaVendorAdapter(this.jpaVendorAdapter()); 44 45 return emf; 46 } 47 }