Skip to content

Commit

Permalink
write a line into test.file
Browse files Browse the repository at this point in the history
  • Loading branch information
huifer committed Aug 20, 2023
1 parent 38a1be3 commit b6a19c3
Show file tree
Hide file tree
Showing 11 changed files with 671 additions and 0 deletions.
135 changes: 135 additions & 0 deletions docs/spring/cs858fd53a-3f01-11ee-a772-acde48001122.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package com.huifer.bigfile.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicInteger;

/**
* 限流下载service
*/
@Service
public class LimiterFileService {
/**
* 下载计数器:记录有多少个下载请求
*/
public static final AtomicInteger DOWNLOAD_NUM = new AtomicInteger();
protected static final Logger log = LoggerFactory.getLogger(LimiterFileService.class);
/**
* 最大下载速度,单位:kb
*/
@Value("${max.download.speed}")
public int maxDownloadSpeed;


public void downloadBreak(String name, HttpServletRequest request, HttpServletResponse response) {


}


/**
* 限流下载
* // TODO: 2019/9/2 下载暂停会出现异常
*
* @param exportUrl 下载文件url
* @param speed 速度
* @param response response
*/
public void downloadLimit(String exportUrl, int speed, HttpServletResponse response) {
OutputStream out = null;
String fileName = exportUrl.substring(exportUrl.lastIndexOf('/') + 1);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
int downloadSpeed = speed;

try (
InputStream fileInputStream = new FileInputStream(exportUrl);
) {
BandwidthLimiter bandwidthLimiter = new BandwidthLimiter(downloadSpeed);
DownloadLimiter downloadLimiter = new DownloadLimiter(fileInputStream, bandwidthLimiter);

out = response.getOutputStream();
int len = 0;
while ((len = downloadLimiter.read()) != -1) {
out.write(len);
bandwidthLimiter.setMaxRate(speed);
}
out.flush();
out.close();
downloadLimiter.close();
} catch (IOException e) {
log.error("下载失败={}", e);
} finally {
closeStream(out, null);
}
}

/**
* 限流下载
*
* @param exportUrl 下载文件url
* @param response response
*/
public void downloadLimit(String exportUrl, HttpServletResponse response) {
DOWNLOAD_NUM.incrementAndGet();
OutputStream out = null;
DownloadLimiter downloadLimiter = null;
String fileName = exportUrl.substring(exportUrl.lastIndexOf('/') + 1);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

try (InputStream fileInputStream = new FileInputStream(exportUrl);) {
int downloadSpeed = maxDownloadSpeed / DOWNLOAD_NUM.get();
BandwidthLimiter bandwidthLimiter = new BandwidthLimiter(downloadSpeed);
downloadLimiter = new DownloadLimiter(fileInputStream, bandwidthLimiter);
out = response.getOutputStream();
int len = 0;
while ((len = downloadLimiter.read()) != -1) {
out.write(len);
bandwidthLimiter.setMaxRate(maxDownloadSpeed / DOWNLOAD_NUM.get());
}
out.flush();
out.close();
downloadLimiter.close();
} catch (IOException e) {
log.error("下载失败={}", e);
} finally {
closeStream(out, downloadLimiter);
}
DOWNLOAD_NUM.decrementAndGet();
}

/**
* 关闭流
*
* @param out OutputStream
* @param downloadLimiter DownloadLimiter
*/
protected void closeStream(OutputStream out, DownloadLimiter downloadLimiter) {
if (out != null) {
try {
out.close();
} catch (IOException e) {
log.error("输出流关闭失败{}", e);
}
}
if (downloadLimiter != null) {
try {
downloadLimiter.close();
} catch (IOException e) {
log.error("下载限流关闭失败={}", e);
}
}
}


}
93 changes: 93 additions & 0 deletions docs/spring/cs85d051b4-3f01-11ee-a772-acde48001122.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* Copyright 2009-2019 the original author or authors.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.ibatis.mapping;

import org.apache.ibatis.builder.InitializingObject;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;

import static com.googlecode.catchexception.apis.BDDCatchException.caughtException;
import static com.googlecode.catchexception.apis.BDDCatchException.when;
import static org.assertj.core.api.BDDAssertions.then;

class CacheBuilderTest {

@Test
void testInitializing() {
InitializingCache cache = unwrap(new CacheBuilder("test").implementation(InitializingCache.class).build());

Assertions.assertThat(cache.initialized).isTrue();
}

@Test
void testInitializingFailure() {
when(() -> new CacheBuilder("test").implementation(InitializingFailureCache.class).build());
then(caughtException()).isInstanceOf(CacheException.class)
.hasMessage("Failed cache initialization for 'test' on 'org.apache.ibatis.mapping.CacheBuilderTest$InitializingFailureCache'");
}

@SuppressWarnings("unchecked")
private <T> T unwrap(Cache cache) {
Field field;
try {
field = cache.getClass().getDeclaredField("delegate");
} catch (NoSuchFieldException e) {
throw new IllegalStateException(e);
}
try {
field.setAccessible(true);
return (T) field.get(cache);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} finally {
field.setAccessible(false);
}
}

private static class InitializingCache extends PerpetualCache implements InitializingObject {

private boolean initialized;

public InitializingCache(String id) {
super(id);
}

@Override
public void initialize() {
this.initialized = true;
}

}

private static class InitializingFailureCache extends PerpetualCache implements InitializingObject {

public InitializingFailureCache(String id) {
super(id);
}

@Override
public void initialize() {
throw new IllegalStateException("error");
}

}

}
94 changes: 94 additions & 0 deletions docs/spring/cs860d1cd4-3f01-11ee-a772-acde48001122.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* Copyright 2009-2019 the original author or authors.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.ibatis.type;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class EnumOrdinalTypeHandlerTest extends BaseTypeHandlerTest {

private static final TypeHandler<MyEnum> TYPE_HANDLER = new EnumOrdinalTypeHandler<MyEnum>(MyEnum.class);

@Override
@Test
public void shouldSetParameter() throws Exception {
TYPE_HANDLER.setParameter(ps, 1, MyEnum.ONE, null);
verify(ps).setInt(1, 0);
}

@Test
public void shouldSetNullParameter() throws Exception {
TYPE_HANDLER.setParameter(ps, 1, null, JdbcType.VARCHAR);
verify(ps).setNull(1, JdbcType.VARCHAR.TYPE_CODE);
}

@Override
@Test
public void shouldGetResultFromResultSetByName() throws Exception {
when(rs.getInt("column")).thenReturn(0);
when(rs.wasNull()).thenReturn(false);
assertEquals(MyEnum.ONE, TYPE_HANDLER.getResult(rs, "column"));
}

@Override
@Test
public void shouldGetResultNullFromResultSetByName() throws Exception {
when(rs.getInt("column")).thenReturn(0);
when(rs.wasNull()).thenReturn(true);
assertNull(TYPE_HANDLER.getResult(rs, "column"));
}

@Override
@Test
public void shouldGetResultFromResultSetByPosition() throws Exception {
when(rs.getInt(1)).thenReturn(0);
when(rs.wasNull()).thenReturn(false);
assertEquals(MyEnum.ONE, TYPE_HANDLER.getResult(rs, 1));
}

@Override
@Test
public void shouldGetResultNullFromResultSetByPosition() throws Exception {
when(rs.getInt(1)).thenReturn(0);
when(rs.wasNull()).thenReturn(true);
assertNull(TYPE_HANDLER.getResult(rs, 1));
}

@Override
@Test
public void shouldGetResultFromCallableStatement() throws Exception {
when(cs.getInt(1)).thenReturn(0);
when(cs.wasNull()).thenReturn(false);
assertEquals(MyEnum.ONE, TYPE_HANDLER.getResult(cs, 1));
}

@Override
@Test
public void shouldGetResultNullFromCallableStatement() throws Exception {
when(cs.getInt(1)).thenReturn(0);
when(cs.wasNull()).thenReturn(true);
assertNull(TYPE_HANDLER.getResult(cs, 1));
}

enum MyEnum {
ONE, TWO
}

}
Loading

0 comments on commit b6a19c3

Please sign in to comment.