cek array string yang berisi string tertentu

array of string contains string

Bismillah

if (Arrays.asList(new String[]{"satu","dua","tiga","empat"}).contains("empat")){
System.out.println("ada");
} else {
System.out.println("kosong");
}

Hasil coding di atas dijalankan adalah : ada

Alhamdulillah

Advertisements

org.hibernate.LazyInitializationException could not initialize proxy – no Session

Error LazyInitializationException 🙂

Bismillah

q> Ini coding header


package com.saifiahmada.spring.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class HdrTest implements Serializable {

private static final long serialVersionUID = 1L;

@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "HDR_ID" , length=36)
private String hdrId;

@Temporal(TemporalType.TIMESTAMP)
private Date tglTest;

@Column(length = 20)
private String username;

@OneToMany(cascade={CascadeType.ALL})
@JoinColumn(name="hdr_id")
private List<DtlTest> dtlTests;

public String getHdrId() {
return hdrId;
}

public void setHdrId(String hdrId) {
this.hdrId = hdrId;
}

public Date getTglTest() {
return tglTest;
}

public void setTglTest(Date tglTest) {
this.tglTest = tglTest;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public List<DtlTest> getDtlTests() {
return dtlTests;
}

public void setDtlTests(List<DtlTest> dtlTests) {
this.dtlTests = dtlTests;
}
}

q> Ini coding detail


package com.saifiahmada.spring.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class DtlTest implements Serializable {

private static final long serialVersionUID = 1L;

@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "DTL_ID" , length=36)
private String dtlId;

@Column(name="ID_SOAL", length=36)
private String idSoal;

@Column(length=1)
private String jawabanSiswa;

@ManyToOne
@JoinColumn(name="hdr_id")
private HdrTest hdrTest;

public DtlTest() {

}

public String getDtlId() {
return dtlId;
}

public void setDtlId(String dtlId) {
this.dtlId = dtlId;
}

public String getIdSoal() {
return idSoal;
}

public void setIdSoal(String idSoal) {
this.idSoal = idSoal;
}

public String getJawabanSiswa() {
return jawabanSiswa;
}

public void setJawabanSiswa(String jawabanSiswa) {
this.jawabanSiswa = jawabanSiswa;
}

public HdrTest getHdrTest() {
return hdrTest;
}

public void setHdrTest(HdrTest hdrTest) {
this.hdrTest = hdrTest;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dtlId == null) ? 0 : dtlId.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;
DtlTest other = (DtlTest) obj;
if (dtlId == null) {
if (other.dtlId != null)
return false;
} else if (!dtlId.equals(other.dtlId))
return false;
return true;
}

@Override
public String toString() {
return "DtlTest [dtlId=" + dtlId + "]";
}

}

q> Ketika coba mengambil data dengan coding ini


package com.saifiahmada.spring;

import java.util.List;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;

import com.saifiahmada.spring.domain.DtlTest;
import com.saifiahmada.spring.domain.HdrTest;
import com.saifiahmada.spring.repository.HdrTestRepository;

@Configurable
@EnableAutoConfiguration
public class OfflineTest {

public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(OfflineTest.class, args);

HdrTestRepository repo = (HdrTestRepository) ctx.getBean("hdrTestRepository");

List<HdrTest> list = repo.findAll();
for (HdrTest hdr : list) {
System.out.println("" + hdr.getHdrId());
System.out.println("" + hdr.getUsername());
System.out.println("" + hdr.getTglTest());
for (DtlTest dtl : hdr.getDtlTests()) {
System.out.println("" + dtl.getDtlId());
System.out.println("" + dtl.getIdSoal());
System.out.println("" + dtl.getJawabanSiswa());
}
}

}
}

q> Muncul error ini

Exception in thread “main” org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.saifiahmada.spring.domain.HdrTest.dtlTests, could not initialize proxy – no Session

q> Coba kita tambahkan code ini pada header

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)

q> Sehingga coding untuk OneToMany pada header seperti ini :

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="hdr_id")
private List<DtlTest> dtlTests;

q> Berhasil mengambil seluruh header beserta detailnya 🙂

Alhamdulillah

melihat bean yang diload pada spring boot

bean apa saja yang diload ketika spring boot dijalankan

Bismillah


package com.saifiahmada.spring;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;

@Configurable
@EnableAutoConfiguration
public class OfflineTest {

public static void main(String [] args){
ApplicationContext ctx = SpringApplication.run(OfflineTest.class, args);

System.out.println("List beans pada Spring Boot adalah :");

String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}

q> Hasilnya adalah :

List beans pada Spring Boot adalah :
$autoCreateChannelCandidates
DefaultConfiguringBeanFactoryPostProcessor
IntegrationConfigurationBeanFactoryPostProcessor
_org.springframework.integration.errorLogger
authenticationEventPublisher
authenticationManager
authenticationManagerBuilder
autowiredWebSecurityConfigurersIgnoreParents
bankSoalRepository
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
bootDefaultingAuthenticationConfigurerAdapter
bootGlobalAuthenticationConfigurationAdapter
channelInitializer
characterEncodingFilter
converterRegistrar
dataSource
dataSourceInitializedPublisher
dataSourceInitializer
dataSourceInitializerPostProcessor
datatypeChannelMessageConverter
defaultServletHandlerMapping
defaultTemplateResolver
defaultViewResolver
delegatingApplicationListener
dispatcherServlet
dispatcherServletRegistration
embeddedServletContainerCustomizerBeanPostProcessor
enableGlobalAuthenticationAutowiredConfigurer
entityManagerFactory
entityManagerFactoryBuilder
error
errorAttributes
errorChannel
faviconHandlerMapping
faviconRequestHandler
foo
globalChannelInterceptorProcessor
handlerExceptionResolver
hdrTestRepository
hiddenHttpMethodFilter
http.mappers.CONFIGURATION_PROPERTIES
httpRequestHandlerAdapter
ignoredPathsWebSecurityConfigurerAdapter
integrationConversionService
integrationEvaluationContext
integrationGlobalProperties
integrationHeaderChannelRegistry
integrationRequestMappingHandlerMapping
jacksonGeoModule
jacksonObjectMapper
jacksonObjectMapperBuilder
jdbcTemplate
jpaMappingContext
jpaVendorAdapter
kontakRepository
layoutDialect
mappingJackson2HttpMessageConverter
mbeanExporter
mbeanServer
messageBuilderFactory
messageConverters
multipart.CONFIGURATION_PROPERTIES
multipartConfigElement
multipartResolver
mvcContentNegotiationManager
mvcConversionService
mvcPathMatcher
mvcResourceUrlProvider
mvcUriComponentsContributor
mvcUrlPathHelper
mvcValidator
mvcViewResolver
namedParameterJdbcTemplate
nullChannel
objectNamingStrategy
objectPostProcessor
offlineTest
openEntityManagerInViewInterceptor
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration$IntegrationConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$DataSourceInitializerConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$TransactionManagementConfiguration
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration$TomcatDataSourcePoolMetadataProviderConfiguration
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
org.springframework.boot.autoconfigure.jta.JtaAutoConfiguration
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration
org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration
org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration$AuthenticationManagerConfigurationListener
org.springframework.boot.autoconfigure.security.BootGlobalAuthenticationConfiguration
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$WebMvcSecurityConfigurationConditions
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$WebMvcSecurityConfigurationConditions$DefaultWebMvcSecurityConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafSecurityDialectConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafWebLayoutConfiguration
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
org.springframework.boot.autoconfigure.web.GsonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor
org.springframework.data.web.config.SpringDataJacksonConfiguration
org.springframework.data.web.config.SpringDataWebConfiguration
org.springframework.integration.config.IdGeneratorConfigurer#0
org.springframework.integration.expression.IntegrationEvaluationContextAwareBeanPostProcessor#0
org.springframework.integration.internalMessagingAnnotationPostProcessor
org.springframework.orm.jpa.SharedEntityManagerCreator#0
org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration
org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration
org.springframework.security.config.annotation.web.servlet.configuration.WebMvcSecurityConfiguration
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
org.springframework.transaction.config.internalTransactionAdvisor
pageableResolver
persistenceExceptionTranslationPostProcessor
privilegeEvaluator
propertySourcesPlaceholderConfigurer
requestContextListener
requestDataValueProcessor
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
roleRepository
runnumRepository
securityDialect
securityFilterChainRegistration
securityProperties
serverProperties
simpleControllerHandlerAdapter
sortResolver
spring.datasource.CONFIGURATION_PROPERTIES
spring.http.encoding.CONFIGURATION_PROPERTIES
spring.jackson.CONFIGURATION_PROPERTIES
spring.jpa.CONFIGURATION_PROPERTIES
spring.jta.CONFIGURATION_PROPERTIES
spring.mvc.CONFIGURATION_PROPERTIES
spring.resources.CONFIGURATION_PROPERTIES
spring.thymeleaf.CONFIGURATION_PROPERTIES
springSecurityFilterChain
stringHttpMessageConverter
taskScheduler
tempRepository
templateEngine
thymeleafResourceResolver
thymeleafViewResolver
toStringFriendlyJsonNodeToStringConverter
tomcatEmbeddedServletContainerFactory
tomcatPoolDataSourceMetadataProvider
transactionAttributeSource
transactionInterceptor
transactionManager
userRepository
viewControllerHandlerMapping
viewResolver
webSecurityExpressionHandler
websocketContainerCustomizer

Alhamdulillah

install code completion thymeleaf on eclipse

Eclipse sts kq ga jalan code completionnya untuk thymeleaf ?

Bismillah

q> Buka eclipse (STS) > Help > Install New Software >

Add > http://www.thymeleaf.org/eclipse-plugin-update-site/

q> Kemudian install > Restart Eclipse (STS)

q> Coba code completion , ketika th: kemudian ctrl + space

Alhamdulillah

install tinymce pada thymeleaf

Coba tinymce pada thymeleaf

Bismillah

Sebelumnya sudah mencoba untuk menggunakan tinymce di html biasa, bagaiama klo di Thymeleaf ?

q> Konsepnya sama dengan menggunakan di html

q> Donwload , extract, kemudian panggil pada file htmlnya

q> Karena thymeleaf disini menggunakan spring boot, maka kita tambahkan registry untuk resourceHandlernya seperti ini :

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/bootstrap/**").addResourceLocations("classpath:/static/bootstrap/3.1.0/");
registry.addResourceHandler("/jq/**").addResourceLocations("classpath:/static/jquery/");
registry.addResourceHandler("/jqueryui/**").addResourceLocations("classpath:/static/jqueryui/");
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
registry.addResourceHandler("/datepicker/**").addResourceLocations("classpath:/static/datepicker/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/tinymce/**").addResourceLocations("classpath:/static/tinymce/");
/*linux*/
//registry.addResourceHandler("/foto/**").addResourceLocations("file:///home/saifi/Desktop/foto/");
/*windows*/


}

q> Ini coding untuk htmlnya :


<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Coba TinyMce</title>
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}" />
<script type="text/javascript" th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/tinymce/js/tinymce/tinymce.min.js}"></script>

<script type="text/javascript">
tinymce.init({
selector: '#mytextarea',
images_upload_base_path: '/some/basepath'
});
</script>
</head>
<body>

<div th:include="header :: header"></div>
<div class="container">
<h1 th:inline="text">Coba TinyMce</h1>
<form action="" th:action="@{/soal/processtiny/}" method="post">
<textarea id="mytextarea" name="data" rows="" cols=""></textarea><br/>
<input type="submit" value="Kirim" class="btn btn-success" />
</form>
<label th:text="${hasil}">tes</label>

</div>

</body>
</html>

q> Dan ini untuk controllernya :

@RequestMapping(value = "/cobatiny", method = RequestMethod.GET)
public String cobaTinyMce(){
return "cobatiny";
}
@RequestMapping(value = "/processtiny", method = RequestMethod.POST)
public String processTiny(@RequestParam("data") String data, Model model){
model.addAttribute("hasil", data);
return "cobatiny";
}

q> Dan hasilnya adalah :
coba_tinymce_thymeleaf

 

Alhamdulillah

@Secured pada controller spring boot

Bagaiamana sebuah controller pada aplikasi spring boot hanya bisa diakases oleh user yang mempunyai ROLE admin ?

Bismillah

misalnya kita mempunyai sebuah controller seperti ini :

@Controller
@RequestMapping("/kontak")
@Secured("ROLE_ADMIN")
public class KontakController {
@RequestMapping("/save")
public void save(){
}
}

Maka untuk mengakses controller tersebut hanya user-user yang mempunyai role admin saja yang bisa mengaksesnya, selain user tersebut maka akan muncul error Access is denied

Catatan :
aplikasi menggunakan spring boot, spring data jpa, spring security, thymeleaf dan database mariadb

Alhamdulillah

@lob menghasilkan longtext mysql

Ternyata @lob menghasilkan longtext pada mysql

Bismillah

Test coding ini 🙂

private static final long serialVersionUID = 1L;
@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(length=64)
private String id;

@Lob
private String teks;

private String pilihanA;

private String pilihanB;

private String pilihanC;

private String pilihanD;

private String pilihanE;
@Column(length=1)
private String jawaban;
@Column(length=25)
private String tipe;

q> Ketika di-build ( / + running code)Menghasilkan table seperti ini :

testcode

Alhamdulillah