반응형

1. 확장된 디스크 크기가 보이는지 확인

lsblk
fdisk -l

 

2. pv확장

pvresize /dev/sda2

 

3. VG(Volume Group) 확인

vgdisplay
(확장된 Free PE (Physical Extent) 용량이 보이면 성공)

 

4. LV(Logical Volume) 확장

lvextend -l +100%FREE /dev/mapper/centos-root
(경로는 lvdisplay로 확인)

 

5. 파일시스템 확장

(CentOS7 기본 루트 파일시스템인 경우)
xfs_growfs /

(EXT4 인 경우)
resize2fs /dev/centos/root

 

6. 확인

df -h
반응형

'Linux' 카테고리의 다른 글

apache complie include module  (0) 2022.05.27
ubuntu apt source kakao  (0) 2016.12.29
SSL 인증서 변환  (0) 2013.03.11
ubuntu ssh 로그인 실패 아이피 차단  (0) 2013.02.20
쉘프로그래밍 기초  (0) 2012.01.25
반응형

Maven Dependency Plugin을 사용하여 의존성만 복사하기

Maven Dependency Plugin을 사용하면 의존성 JAR 파일만을 특정 폴더로 복사할 수 있습니다.

<!--
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>3.3.0</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			-->

			<!-- libs_export 경로에 의존성jar 별도 복사 -->
			<plugin>
		      <groupId>org.apache.maven.plugins</groupId>
		      <artifactId>maven-dependency-plugin</artifactId>
		      <version>3.3.0</version>
		      <executions>
		        <execution>
		          <id>copy-dependencies</id>
		          <phase>package</phase>
		          <goals>
		            <goal>copy-dependencies</goal>
		          </goals>
		          <configuration>
		            <outputDirectory>${project.build.directory}/libs_export</outputDirectory>
		          </configuration>
		        </execution>
		      </executions>
		    </plugin>

 

반응형

'java' 카테고리의 다른 글

logback  (0) 2021.12.22
java proxy  (0) 2021.04.07
JAVA 정규식 html javascript 삭제  (0) 2020.12.10
spring poi excel download  (0) 2020.10.22
JAVA File to byte []  (0) 2013.01.11
반응형

Header edit Set-Cookie ^(.*)$ "$1; SameSite=None;"
Header edit Allow ^(.*)$ ""

 

 

추가

반응형

'Etc.' 카테고리의 다른 글

gitea dark-theme  (0) 2024.01.08
Sourcetree 외부 비교 도구 VisualCode  (0) 2022.11.09
니코틴 계산  (0) 2019.11.06
단축키 비교표 IntelliJ, Eclipse, Visual Studio  (0) 2019.09.26
VLC streaming  (0) 2017.08.03
반응형

https://docs.theme-park.dev/themes/gitea/#click-here-for-general-setup

 

Gitea ⚙️ - theme.park Docs

Gitea Custom Gitea CSS 🛠️ Installation Info Tested on Version: 1.15.4 If you want to add the theme with subfilter ect, click here: https://docs.theme-park.dev/setup/#methods The theme is built on top of the Gitea theme, so make sure that is selected i

docs.theme-park.dev

 

 

make file

gitea/templates/custom/body_outer_pre.tmpl

 

add

{{ if .IsSigned }}
  {{ if and (ne .SignedUser.Theme "gitea") (ne .SignedUser.Theme "arc-green") }}
    <link rel="stylesheet" href="https://theme-park.dev/css/base/gitea/{{.SignedUser.Theme}}.css">
  {{end}}
{{ else if and (ne DefaultTheme "gitea") (ne DefaultTheme "arc-green") }}
  <link rel="stylesheet" href="https://theme-park.dev/css/base/gitea/{{DefaultTheme}}.css">
{{end}}

 

edit file

gitea/conf/app.ini

 

[ui] 
THEMES = gitea,arc-green,plex,aquamarine,dark,dracula,hotline,organizr,space-gray,hotpink,onedark,overseerr,nord 
DEFAULT_THEME = gitea

 

 

 

 

 

 

반응형

'Etc.' 카테고리의 다른 글

apache samesite  (0) 2024.01.09
Sourcetree 외부 비교 도구 VisualCode  (0) 2022.11.09
니코틴 계산  (0) 2019.11.06
단축키 비교표 IntelliJ, Eclipse, Visual Studio  (0) 2019.09.26
VLC streaming  (0) 2017.08.03
반응형

https://access.redhat.com/webassets/avalon/d/red_hat_jboss_enterprise_application_platform/7.3/mgmt_model/subsystem/undertow/server/ajp-listener/index.html

반응형

'Jboss' 카테고리의 다른 글

jboss enable cors  (0) 2023.07.31
WildFly clustering  (0) 2020.12.19
반응형
$ ./jboss-cli.sh -c
/subsystem=undertow/configuration=filter/response-header="Access-Control-Allow-Origin":add(header-name="Access-Control-Allow-Origin",header-value="*")
/subsystem=undertow/configuration=filter/response-header="Access-Control-Allow-Methods":add(header-name="Access-Control-Allow-Methods",header-value="GET, POST, HEAD")
/subsystem=undertow/configuration=filter/response-header="Access-Control-Allow-Headers":add(header-name="Access-Control-Allow-Headers",header-value="accept, authorization, content-type, x-requested-with, cache-control")
/subsystem=undertow/configuration=filter/response-header="Access-Control-Allow-Credentials":add(header-name="Access-Control-Allow-Credentials",header-value="true")
/subsystem=undertow/configuration=filter/response-header="Access-Control-Max-Age":add(header-name="Access-Control-Max-Age",header-value="1")

 

/subsystem=undertow/server=default-server/host=default-host/filter-ref="Access-Control-Allow-Origin":add()
/subsystem=undertow/server=default-server/host=default-host/filter-ref="Access-Control-Allow-Methods":add()
/subsystem=undertow/server=default-server/host=default-host/filter-ref="Access-Control-Allow-Headers":add()
/subsystem=undertow/server=default-server/host=default-host/filter-ref="Access-Control-Allow-Credentials":add()
/subsystem=undertow/server=default-server/host=default-host/filter-ref="Access-Control-Max-Age":add()

 

 

 

jboss eap 6

<subsystem xmlns="urn:jboss:domain:web:2.2" default-virtual-server="default-host" native="false">
    <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
    <virtual-server name="default-host" enable-welcome-root="true">
        <alias name="localhost"/>
        <alias name="example.com"/>
        <rewrite pattern=".*" substitution="-" flags="F">
            <condition test="%{REQUEST_METHOD}" pattern="^(PUT|DELETE|TRACE|OPTIONS)$" flags="NC" />
        </rewrite>
    </virtual-server> 
</subsystem>​



반응형

'Jboss' 카테고리의 다른 글

jboss ajp listener options  (0) 2023.12.13
WildFly clustering  (0) 2020.12.19

반응형

 

 

Visual Code경로 : C:\Users\%USERNAME%\AppData\Local\Programs\Microsoft VS Code\Code.exe
diff : -n -w -d $LOCAL $REMOTE
병합 : -n -w $MERGED

 

 

반응형

'Etc.' 카테고리의 다른 글

apache samesite  (0) 2024.01.09
gitea dark-theme  (0) 2024.01.08
니코틴 계산  (0) 2019.11.06
단축키 비교표 IntelliJ, Eclipse, Visual Studio  (0) 2019.09.26
VLC streaming  (0) 2017.08.03
반응형
제한된 인터넷 환경을 위한 apache 컴파일



- 필요한 모듈 압축 풀고 httpd소스 srclib 경로로 넣어줌

mv apr httpd-2.4.53/srclib/apr
mv apr-util httpd-2.4.53/srclib/apr-util
mv pcre httpd-2.4.53/srclib/pcre

- 컴파일

./configure --prefix=/usr/local/apache-2.4.54 --with-included-apr --with-included-apr-util --with-include-pcre --enable-mpms-shared=all --enable-so --with-mpm=event
make
make install

- 압축
tar -zcvf compiled_apache_2.4.54.tar.gz apache-2.4.54


- 테스트

 

 

 

반응형

'Linux' 카테고리의 다른 글

ESXi centos linux 용량 늘리기  (0) 2025.09.22
ubuntu apt source kakao  (0) 2016.12.29
SSL 인증서 변환  (0) 2013.03.11
ubuntu ssh 로그인 실패 아이피 차단  (0) 2013.02.20
쉘프로그래밍 기초  (0) 2012.01.25
반응형

 

<!-- pom.xml -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.3.14</version>
</dependency>

<dependency>
    <groupId>org.lazyluke</groupId>
    <artifactId>log4jdbc-remix</artifactId>
    <version>0.2.7</version>
</dependency>

<!--
<exclusions>
    <exclusion>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </exclusion>
    <exclusion>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
    </exclusion>
    <exclusion>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
    </exclusion>
    <exclusion>
        <groupId>egovframework.rte</groupId>
        <artifactId>egovframework.rte.fdl.logging</artifactId>
    </exclusion>
</exclusions>
-->


<!-- logback.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="false" scanPeriod="30 seconds">

	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg\n</pattern>
		</encoder>
	</appender>

	<appender name="console" class="ch.qos.logback.classic.AsyncAppender">
		<discardingThreshold>0</discardingThreshold>
		<queueSize>65536</queueSize>
		<appender-ref ref="console" />
	</appender>
	
	
	<!-- SQL Logger -->
	<logger name="jdbc" 				level="OFF" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="jdbc.sqlonly" 		level="INFO" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="jdbc.sqltiming" 		level="INFO" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="jdbc.audit" 			level="OFF" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="jdbc.resultset" 		level="OFF" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="jdbc.resultsettable" 	level="INFO" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="jdbc.connection" 		level="OFF" 	additivity="false"> <appender-ref ref="console" /> </logger>

	<logger name="java.sql" 			level="INFO" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="egovframework" 		level="DEBUG" 	additivity="false"> <appender-ref ref="console" /> </logger>
	<logger name="org.springframework" 	level="INFO" 	additivity="false"> <appender-ref ref="console" /> </logger>

	<root level="INFO">
		<appender-ref ref="console" />
	</root>
	

</configuration>



<!-- datasource -->
<!-- cubrid -->
<bean id="dataSource-cubrid-spied" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${Globals.DriverClassName}"/>
    <property name="url" value="${Globals.Url}" />
    <property name="username" value="${Globals.UserName}"/>
    <property name="password" value="${Globals.Password}"/>
</bean>

<bean id="dataSource-cubrid" class="net.sf.log4jdbc.Log4jdbcProxyDataSource">
    <constructor-arg ref="dataSource-cubrid-spied" />
    <property name="logFormatter">
        <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter">
            <property name="loggingType" value="MULTI_LINE" />
            <property name="sqlPrefix" value="SQL::::      " />
        </bean>
    </property>
</bean>

 

 

 

 

반응형

'java' 카테고리의 다른 글

Maven Dependency Plugin을 사용하여 의존성만 복사하기  (0) 2024.09.09
java proxy  (0) 2021.04.07
JAVA 정규식 html javascript 삭제  (0) 2020.12.10
spring poi excel download  (0) 2020.10.22
JAVA File to byte []  (0) 2013.01.11
반응형
@GetMapping(value="/proxy.do")
    public void mapViewProxy(HttpServletRequest request, HttpServletResponse response, @RequestParam String p) {

        String queryString = request.getQueryString();
        String param = queryString.substring(2, queryString.length());

        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store");
        //request.setCharacterEncoding("utf-8");

        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(param);
        //PostMethod method = new PostMethod(param);
        String contentType = request.getContentType();
        //method.setRequestBody(xml);
        method.setRequestHeader("Content-type", contentType);
        //method.setRequestBody(request.getInputStream());

        String result = null;
        try {
            int statusCode = client.executeMethod(method);
            result = method.getResponseBodyAsString();
            System.out.println(result);
            System.out.println(statusCode);

            response.reset();
            response.setStatus(statusCode);

            response.setContentType("text/xml; charset=utf-8"); //외부 사이트의 결과를 프록시의 응답결과로 전송


            PrintWriter out = response.getWriter();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            out.print(result);
            out.flush();


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
반응형

'java' 카테고리의 다른 글

Maven Dependency Plugin을 사용하여 의존성만 복사하기  (0) 2024.09.09
logback  (0) 2021.12.22
JAVA 정규식 html javascript 삭제  (0) 2020.12.10
spring poi excel download  (0) 2020.10.22
JAVA File to byte []  (0) 2013.01.11
반응형

jboss-cli

 

  /socket-binding-group=standard-sockets/socket-binding=jgroups-tcp:write-attribute(name=port,value=7600)
  /socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=node10:add(host=192.168.187.128,port=7600)
  /socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=node20:add(host=192.168.187.130,port=7600)
  /subsystem=jgroups/channel=ee:write-attribute(name=stack,value=tcp)
  /subsystem=jgroups/stack=tcp/protocol=MPING:remove()
  /subsystem=jgroups/stack=tcp/protocol=TCPPING:add(socket-bindings=[node10,node20])

 

reload

반응형

'Jboss' 카테고리의 다른 글

jboss ajp listener options  (0) 2023.12.13
jboss enable cors  (0) 2023.07.31
반응형
package com.example.demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {
	
	/**
	 * script 삭제 
	 * @param oldText
	 * @return
	 */
	private String removeScriptXSS(String oldText) {
		String regex = "<script(?:[^>]*src=['\"]([^'\"]*)['\"][^>]*>|[^>]*>([^<]*)</script>)";
	    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		StringBuffer sb = new StringBuffer();
		Matcher matcher = pattern.matcher(oldText);
        while (matcher.find()) {
        	matcher.appendReplacement(sb, "");
        }
        matcher.appendTail(sb);
        return sb.toString();
	}

	@GetMapping("/greeting.do")
	public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
		
		String cont = "<div class=\"skin_view\">\n"
				+ "								<h2 id=\"dkBody\" class=\"screen_out\">티스토리 뷰</h2>\n"
				+ "								<div class=\"area_title\">\n"
				+ "									<strong class=\"tit_category\"><a href=\"/category/Programming/JSP\">Programming/JSP</a></strong>\n"
				+ "			<Script type=\"text/javaScript\">alert(1111111);</scripT>"
				+ "									<h3 class=\"tit_post\"><a href=\"/26\">[JSP]JSP 프로젝트 생성 및 설정</a></h3>\n"
				+ "									<span class=\"txt_detail my_post\">heyhyo\n"
				+ "			<Script type=\"application/javascript\">alert(444444);"
				+ "      alert('7777777777');"
				+ "                   </scripT>"
				+ "										<span class=\"txt_bar\"></span>2018. 8. 7. 15:32\n"
				+ "										\n"
				+ "			<Script>alert(222222);</scripT>"
				+ "									</span>\n"
				+ "								</div>\n"
				+ "								<div class=\"area_view\">"
				+ "</div></div>";
		
		model.addAttribute("name", removeScriptXSS(cont));
		
		return "greeting";
	}

}
반응형

'java' 카테고리의 다른 글

logback  (0) 2021.12.22
java proxy  (0) 2021.04.07
spring poi excel download  (0) 2020.10.22
JAVA File to byte []  (0) 2013.01.11
[RCP] "org.eclipse.ui.ide.workbench" could not be found in the registry  (0) 2012.01.26
반응형
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>  
@RequestMapping("/excel")
public void excel(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

	String fileName = "test_excel.xlsx";

	// 여기서부터는 각 브라우저에 따른 파일이름 인코딩작업
	String browser = request.getHeader("User-Agent");
	if (browser.indexOf("MSIE") > -1) {
		fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
	} else if (browser.indexOf("Trident") > -1) { // IE11
		fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
	} else if (browser.indexOf("Firefox") > -1) {
		fileName = "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	} else if (browser.indexOf("Opera") > -1) {
		fileName = "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	} else if (browser.indexOf("Chrome") > -1) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < fileName.length(); i++) {
			char c = fileName.charAt(i);
			if (c > '~') {
				sb.append(URLEncoder.encode("" + c, "UTF-8"));
			} else {
				sb.append(c);
			}
		}
		fileName = sb.toString();
	} else if (browser.indexOf("Safari") > -1) {
		fileName = "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	} else {
		fileName = "\"" + new String(fileName.getBytes("UTF-8"), "8859_1") + "\"";
	}

	response.setContentType("application/download;charset=utf-8");
	response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
	response.setHeader("Content-Transfer-Encoding", "binary");

	OutputStream os = null;
	SXSSFWorkbook wb = null;
	Sheet sheet = null;

	try {
		wb = new SXSSFWorkbook();

		sheet = wb.createSheet("test");

		Row row = sheet.createRow(0);
		Cell cell = null;
		cell = row.createCell(0);
		cell.setCellValue("a");
		cell = row.createCell(1);
		cell.setCellValue("b");
		cell = row.createCell(2);
		cell.setCellValue("c");

		os = response.getOutputStream();

		// 파일생성
		wb.write(os);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (wb != null) {
			try {
				wb.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (os != null) {
			try {
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

 

반응형

'java' 카테고리의 다른 글

java proxy  (0) 2021.04.07
JAVA 정규식 html javascript 삭제  (0) 2020.12.10
JAVA File to byte []  (0) 2013.01.11
[RCP] "org.eclipse.ui.ide.workbench" could not be found in the registry  (0) 2012.01.26
java File Delete  (0) 2011.03.03
반응형
package hello;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.coverage.grid.io.GridCoverage2DReader;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.geometry.Envelope;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;

public class TestGeoTools {

  /**
     * GeoTIFF to PNG 변경
     * 
     * @param sourceFilePath
     * @param targetFilePath
     * @return boolean
     * @throws IOException
     */
  public static boolean convertGeoTiffToPng(String sourceFilePath, String targetFilePath) throws IOException {

    File file = new File(sourceFilePath);

    if (!file.exists()) {
      System.out.println("file not found");
      return false;
    }

    // AbstractGridFormat format = GridFormatFinder.findFormat(file);
    // System.out.println(format.getName());
    BufferedImage img = ImageIO.read(file);

    int width = img.getWidth();
    int height = img.getHeight();

    Raster raster = img.getData();
    int bands = raster.getNumBands();

    System.out.println("raster bands: " + bands);

    BufferedImage saveimage = null;
    WritableRaster dest = null;

    switch (bands) {
    case 1:
      saveimage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
      saveimage.createGraphics().drawImage(img, 0, 0, Color.white, null);
      break;
    case 3:
      // Create an identically-sized output raster
      dest = raster.createCompatibleWritableRaster();

      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          // Copy the pixel
          double[] pixel = new double[bands];
          pixel = raster.getPixel(x, y, pixel);
          if (pixel[0] > 255 && pixel[0] > 255 && pixel[0] > 255) {
            pixel[0] = 255;
            pixel[1] = 255;
            pixel[2] = 255;
          }
          dest.setPixel(x, y, pixel);
        }
      }

      // Save the raster back to the Image
      saveimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      saveimage.setData(dest);

      break;
    case 4:
      // Create an identically-sized output raster
      dest = raster.createCompatibleWritableRaster();

      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          // Copy the pixel
          double[] pixel = new double[bands];
          pixel = raster.getPixel(x, y, pixel);
          dest.setPixel(x, y, pixel);
        }
      }

      // Save the raster back to the Image
      saveimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      saveimage.setData(dest);

      break;
    }
    // Write the new file
    ImageIO.write(saveimage, "png", new File(targetFilePath));
    return true;

  }

  /**
     * GeoTIFF 에서 Extent값 가져옴
     * 
     * @param sourceFilePath
     * @return extent
     * @throws IOException
     */
  public static double[] getExtentFromGeoTiff(String sourceFilePath) throws IOException {

    File file = new File(sourceFilePath);
    AbstractGridFormat format = GridFormatFinder.findFormat(file);
    GridCoverage2DReader reader = format.getReader(file);
    GridCoverage2D coverage = (GridCoverage2D) reader.read(null);
    Envelope env = coverage.getEnvelope();

    double minX = env.getLowerCorner().getOrdinate(0);
    double minY = env.getLowerCorner().getOrdinate(1);
    double maxX = env.getUpperCorner().getOrdinate(0);
    double maxY = env.getUpperCorner().getOrdinate(1);

    System.out.println("getGeoTiffExtent=" + coverage.getCoordinateReferenceSystem2D().getName().toString() + " " + coverage.getName() + ": " + minX + "," + minY + "  " + maxX + "," + maxY);

    double[] extent = new double[4];
    extent[0] = minX;
    extent[1] = minY;
    extent[2] = maxX;
    extent[3] = maxY;

    return extent;
  }

  /**
     * SHP파일에서 GeoJson가져옴
     * 
     * @param shpFilePath
     * @param charset
     * @param mapEPSG
     * @param bbox
     * @return geojson string
     * @throws IOException
     * @throws NoSuchAuthorityCodeException
     * @throws FactoryException
     * @throws TransformException
     * @throws CQLException
     */
  public static String getGeoJsonFromShp(String shpFilePath, String charset, String mapEPSG, String bbox)
  throws IOException,
  NoSuchAuthorityCodeException,
  FactoryException,
  TransformException,
  CQLException {

    // 파일 읽기
    File file = new File(shpFilePath);
    Map < String,
    Object > map = new HashMap < >();
    map.put("url", file.toURI().toURL());
    map.put("create spatial index", true);
    map.put("charset", charset); // encode

    System.out.println("charset::" + charset);

    DataStore dataStore = DataStoreFinder.getDataStore(map);
    String typeName = dataStore.getTypeNames()[0];
    FeatureSource < SimpleFeatureType,
    SimpleFeature > source = dataStore.getFeatureSource(typeName);

    CRSAuthorityFactory factory = CRS.getAuthorityFactory(true);

    CoordinateReferenceSystem mapCRS = factory.createCoordinateReferenceSystem(mapEPSG); // CRS.decode(srsName);
    CoordinateReferenceSystem srcCRS = dataStore.getSchema(typeName).getCoordinateReferenceSystem();
    System.out.println("dataCRS.toWKT() :: " + srcCRS.toWKT());
    System.out.println("mapCRS.toWKT() :: " + mapCRS.toWKT());

    boolean lenient = true; // allow for some error due to different datums
    MathTransform transform = CRS.findMathTransform(mapCRS, srcCRS, lenient);

    String[] bbox_str = bbox.split(",");

    double[] param_bbox = new double[4];
    param_bbox[0] = Double.parseDouble(bbox_str[0]);
    param_bbox[1] = Double.parseDouble(bbox_str[1]);
    param_bbox[2] = Double.parseDouble(bbox_str[2]);
    param_bbox[3] = Double.parseDouble(bbox_str[3]);

    double[] srcProjec1 = {
      param_bbox[0],
      param_bbox[1]
    }; // easting, northing,
    double[] srcProjec2 = {
      param_bbox[2],
      param_bbox[3]
    }; // easting, northing,

    double[] dstProjec1 = {
      0,
      0
    };
    double[] dstProjec2 = {
      0,
      0
    };

    transform.transform(srcProjec1, 0, dstProjec1, 0, 1);
    transform.transform(srcProjec2, 0, dstProjec2, 0, 1);

    String filter_bbox = dstProjec1[0] + "," + dstProjec1[1] + "," + dstProjec2[0] + "," + dstProjec2[1];
    System.out.println("filter_bbox: " + filter_bbox);

    Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM, 10,20,30,40)")
    if (!filter_bbox.isEmpty()) {
      filter = ECQL.toFilter("BBOX(the_geom," + filter_bbox + ")"); // ECQL.toFilter("BBOX(THE_GEOM,
      // 10,20,30,40)")
    }

    FeatureCollection < SimpleFeatureType,
    SimpleFeature > collection = source.getFeatures(filter);

    FeatureJSON featureJson = new FeatureJSON();
    StringWriter writer = new StringWriter();
    featureJson.writeFeatureCollection(collection, writer);

    String geojson = writer.toString();

    return geojson;
  }

}
반응형

'GIS' 카테고리의 다른 글

바로e맵 ol v4  (0) 2022.12.13
fabricjs + openlayers test  (0) 2019.12.19
proxy naver test  (0) 2019.12.12
how-to-get-map-units-to-find-current-scale-in-openlayers  (0) 2019.11.15
insert geometry type to geoserver meta table  (0) 2019.09.17

+ Recent posts